jqeury 添加html 元素后 .click 失效问题
<script>
function xxx() {
var abc = '<li><h3 class="geegee">3</h3></li>';
var acc = '<li><h3 class="geegee">4</h3></li>';
output = $(abc + acc);
$('#category').append(output);
}
</script>
<script>
$(document).ready(function() {
$(".geegee").click(function() { //bug
alert("a");
});
});
</script>
自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。该方法给 API 带来很多便利,我们推荐使用该方法,它简化了 jQuery 代码库。使用 on() 方法添加的事件处理程序适用于当前及未来的元素(比如由脚本创建的新元素)
$(".geegee").on("click",function() {
alert("a");
});
委派事件
$("#category").delegate(".geegee","click",function(evt) {
alert("a");
evt.stopPropagation();
});
方法二:追加节点后再调用一次事件方法
function menuItem() {
$('.rightmenu').contextmenu({
target: '.context-menu',
onItem: function (context, e) {
//动态追加参数
var id = context.context.id;
if ($(e.target).context.href.indexOf("/id/") == -1) {
url = $(e.target).context.href;
}
$(e.target).attr("href", url + "/id/" + id);
if ($(e.target).data('operate') == 'copy') {
//todo 显示弹窗
$.get($(e.target).attr("href"), function (json) {
//todo 插入页面位置
$(json.html).insertAfter("#talk_"+id);
menuItem();
});
return;
}
}
});
}
menuItem();