MGE
MGE

Reputation: 853

Problems getting values into a dynamic variable in javascript

selectedsong div has differents links with differents rel=""... and the problems is...

I'm using that:

selectedBtn = $('#selectedsong a');
selectedBtn.click(function()
{
    self.selectedsong($(this).attr('rel'));
    return false;
});

selectedsong: function(number)
{
    $('#selectedsong').html('new content with new links, rel, and more...');
    selectedBtn = $('#selectedsong a'); <---- THE PROBLEM IS HERE,
}

The problem is that, in the first click it works properly, but when the #selectedsong content change, selectedBtn = $('#selectedsong a'); don't work properly, because the selectedBtn.click(function() doesn't work :'(

Thank you very much!

Upvotes: 1

Views: 120

Answers (2)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

Use

$('#selectedsong').on('click','a',function(e)
{
    e.preventDefault(); // prevent default behavior of anchor click

    self.selectedsong($(this).attr('rel'));

    //return false;  dont use return false as it does more work than you need
});
selectedsong: function(number) 
{
  $('#selectedsong').html('new content with new links, rel, and more...');

}

As your HTML content changes you need to use event delegation.

read more on .on()

Upvotes: 1

notbad.jpeg
notbad.jpeg

Reputation: 3368

I think the problem is that you changed the html inside #selectedsong, and that removed your <a> tag from it, and that's what you're trying to do a select on, is the <a> tag inside #selectedsong. Maybe you could try and just select #selectedsong instead of the anchor tag? Or when you change the html, change the html of #selectedsong a.

Upvotes: 0

Related Questions