使用.append(html)创建的jQuery元素不可用
我有以下内容
$(document).ready(function() { $(".mapLink").click(function(){ pos = $(this).attr("id"); alert(pos); }); }); Test
当我点击Test时,我会收到警报……很棒。 但我也有以下……
$(document).ready(function() { $(".mapLink").click(function(){ pos = $(this).attr("id"); alert(pos); }); }); $(#emp").change(function(){ $("#existingAttendTime").html(''); $.ajax({ url: "existingAttendTime.php?emp=" + SelValue + "&time=0", cache: false, success: function(html){ $("#existingAttendTime").append(html); } }); }); Test
当emp更改它会触发并从existingAttendTime.php获取结果并将其插入div中,所以现在看起来像……
Test
单击Test会向我发出警告“test”,但是单击Return Test会让我一无所获。
我做错了什么或我错过了什么?
您需要以“实时”模式绑定单击处理程序,否则新添加的DOM节点将不会触发它:
$(document).ready(function() { $(".mapLink").live("click", function(){ pos = $(this).attr("id"); alert(pos); }); });
曾经有一个实时查询所需的插件,但jQuery 1.3将其有限版本集成到核心中 。 另请注意,只有一些事件类型有效; change
, submit
等不会,因此您必须在将新节点附加到DOM的同一函数内显式附加处理程序。
事件处理程序在DOM上准备好一次 ,如果你操纵DOM,你也需要
- A)手动重新附加事件处理程序
- B)依赖jQuery.prototype.live
它可能更适合使用B,因此我建议将您的点击代码更改为类似…
$("a.mapLink").live("click", function(){ var pos = $(this).attr("id"); alert(pos); });
这将针对通过DOM操作添加的任何锚点。
参考: http : //docs.jquery.com/Events/live
还有,你应该使用var在当前范围内声明pos
。
动态添加项目时, click
处理程序不会在新项目上注册。 相反,使用.live()
:
$(document).ready(function() { $(".mapLink").live('click', function(){ pos = $(this).attr("id"); alert(pos); }); });