我有这个页面:
<html>
<head></head>
<body>
<div id="elem"></div>
<button id="addElem">Add Element</button>
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//add element to elem div
$("#addElem").click(function () {
$("#elem").append('<a id="test" href="#">this is a test</a><br />');
});
//remove added elements on click event
$("#test").on("click", function(){
alert(12);
});
});
</script>
</body>
</html>
它正在做什么,是添加链接,我希望能够点击添加的链接并显示警告消息,但警报无效。我错过了什么?
答案 0 :(得分:5)
将其更改为...
$("#elem").on("click", "#test", function(){
alert(12);
});
jQuery blog对此有很好的解释。
$(elements).on( events [, selector] [, data] , handler );
当提供选择器时,.on()类似于.delegate(),因为它附加了一个由选择器过滤的&gt;委托事件处理程序。当省略选择器或null>时,调用就像.bind()。有一个不明确的情况:如果data参数是一个字符串,则>必须提供一个选择器字符串或null,以便数据不会被误认为是&gt;选择器。传递一个数据对象,你永远不必担心特殊情况。
答案 1 :(得分:1)
您没有活动的锚点。由于您没有其他包装器,请将文档添加到:
$(document).on("click", "#test", function(){
alert(12);
});
注意:这只会在第一次点击时起作用,因为您将添加多个可能重复的ID。
更好的方式:
$("#addElem").click(function () {
$("#elem").append('<a class="test" href="#">this is a test</a><br />');
});
$(document).on("click", ".test", function(){
alert(12);
});
答案 2 :(得分:0)
您可以在创建元素时将该函数附加到创建的元素:
$("#elem").append($('<a>', {
id: "test.
href: "#",
text: "this is a test",
click: function(e){
e.preventDefault();
alert(12);
})
).append($("<br>"));