Некоторые точки
Недостатки:
Профессионалы:
Первая проблема заключается в что, когда вы вызываете append для набора jQuery с более чем одним элементом, для каждого создается клон добавляемого элемента, и, таким образом, прикрепленный наблюдатель событий теряется.
Альтернативный способ сделать это - создать ссылку. для каждого элемента:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
Другая потенциальная проблема может заключаться в том, что наблюдатель событий прикрепляется до того, как элемент был добавлен в DOM. Я не уверен, есть ли здесь что сказать, но я думаю, что такое поведение можно считать неопределенным. Более надежным подходом, вероятно, будет:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
How about the Live method?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
Still, what you did about looks like it should work. There's another post that looks pretty similar.
Consider this:
jQuery(function(){
var close_link = $('<a class="" href="#">Click here to see an alert</a>');
$('.add_to_this').append(close_link);
$('.add_to_this').children().each(function()
{
$(this).click(function() {
alert('hello from binded function call');
//do stuff here...
});
});
});
It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.
The best way will probably be - as suggested - to bind it to a specific class via the live method.
Я считаю, что это хороший способ:
$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );