0
4

3 回答 3

3
于 2012-07-06T02:25:11.917 回答
3

由于元素是动态生成的,因此您需要在方法中使用委托on()或创建文字 jQuery 对象并添加点击事件。

$('closestParent').on('click', 'a', function(){ ... })

// OR

var $link = $('<a href=\'#\'>blah2</a>').click(function(){ ... })
$link.prependTo('#placeholder')
于 2012-07-06T02:27:21.977 回答
0

这是因为您需要将点击委托给父元素。如果您使用的是 1.7+,请使用.on,或者如果您使用的是 1.6 或更低版本,则可以使用 .delegate()。当 dom 准备好时,该元素不存在,因此您需要将事件委托给父元素。这意味着您可以使用$(document)或使用任何已经存在的父元素

$(document).on("click","a", function () {  //<-- this allows for the event to bubble up to the document in this case
        alert('clicked');
});

$(document).delegate("a","click", function () {
        alert('clicked');
});
于 2012-07-06T02:25:37.740 回答