I am trying to append some links with data and a click handler to a containing div.
jQuery 1.4.3
Fails in FireFox 5.0/Chrome 13.0.782, but works in IE9
I first create the element as a jQuery object, then add the data and click handler. Then I use .append() to append it to the container:
var $selector = $('<a href="#" class="x">Test</a>');
$selector.data('testdata', "Test");
$selector.click(function(event) {
alert('Clicked: ' + $(this).data('testdata'));
return false;
});
$('#container').append($selector);
I see the link added, but when I click on it, the click handler does not fire.
I thought that maybe I needed to do the append first and then add data+click, but that doesn't work either:
var $selector = $('<a href="#" class="x">Test</a>');
$('#container').append($selector);
$selector.data('testdata', "Test");
$selector.click(function(event) {
alert('Clicked: ' + $(this).data('testdata'));
return false;
});
Does append not preserve data and handlers? It seems that when I .append($selector), $selector and the newly added DOM object are not one in the same.