在我的应用程序中,我有一个下拉表单,它会在更改时触发 AJAX 请求并返回选定的用户名值,旁边带有“删除”图像。
<div id="el">User Name <img src="ico/del.gif" onclick="ajax_delete(12)" class="del" /></div>
奇怪的是,如果页面是第一次加载,则以下 jQuery 代码会正确执行,并且鼠标指针会在所有 .del 图像上发生变化:
$("img.del").css('cursor', 'pointer');
但是,如果上面的 html 代码是由 AJAX 请求添加的,如下所示:
$("#el").html('User Name <img src="ico/del.gif" onclick="ajax_delete(12)" class="del" />');
鼠标指针更改不适用于 AJAX 请求添加的图像。
知道为什么吗?
最佳答案
运行 css 函数时该元素不存在。您必须在将 css 函数附加到 DOM 后运行它。
.live doesn't support the no-event style callback that liveQuery provides. Only event handlers can be bound with .live.
您需要使用liveQuery plug-in来实现这一点。
从那里开始就非常简单了:
$('#el').livequery(function() {
$(this).css('background', 'green');
});
请注意,liveQuery 还可以通过使用第二个参数来触发已删除或不再匹配的元素(例如,如果您基于值比较进行匹配):
The unmatchedFn is fired when an element changes and is no longer matched or removed from the DOM.
很好。
关于jquery - 为什么 jQuery 的事件处理程序不能处理已更改的 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/839484/