jquery 1.7追加后点击事件不起作用
jquery 1.7 click event after append not working
我正在处理来自http://learn.jquery.com/events/event-delegation/.我有以下代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="A small web app to manage todos">
<title>TO-DO jQuery Tests</title>
<!--src attribute in the <script> element must point to a copy of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "article" ).on( "click","a", function() {
console.log( "The ID attribute of the link is: " + $(this).attr('id'));
});
//The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
$( "#test-container" ).append("<article> <a href='"#'"id='link-2'>Link 2</a> </article>" );
});
</script>
</head>
<body>
<div id="test-container">
<article>
<a href="#" id="link-1">Link 1</a>
</article>
</div>
</body>
当我点击Link2时,控制台上没有输出?为什么事件处理不起作用?
您必须绑定到最近的静态父级
本例为test-container
。
$( "#test-container" ).on( "click","article a", function() {
// your code
});
问题是第二个链接是动态添加的,点击绑定发生在第二个链路存在之前。这就是为什么它对它没有影响。
您的代码应该是这样的(您也可以使用Ricardo指出的任何静态父容器,而不是$(document)
):
$(document).ready(function() {
$(document ).on( "click","article a", function() {
console.log( "The ID attribute of the link is: " + $(this).attr('id'));
});
//The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
$( "#test-container" ).append("<article> <a href='"#'"id='link-2'>Link 2</a> </article>" );
});
相关文章:
- JsFiddle上的鼠标事件不起作用
- 链接上的IE10 jquery句柄单击事件不起作用
- jQuery加载完成事件不起作用
- 覆盖单击事件不起作用
- 单击事件不起作用
- 为什么body元素上的onclick事件不起作用
- 追加Jquery后的Binding Click事件不起作用
- chrome中的onmouseover(下拉选项标记)事件不起作用-php,javascript
- jQuery调用keyup事件不起作用
- 选择选项淘汰赛事件不起作用
- pixijs 鼠标关闭事件不起作用(任何版本)
- D3.js鼠标事件不起作用
- D3js 饼图单击事件不起作用
- j查询动画重置后事件不起作用
- jquery 1.7追加后点击事件不起作用
- 当我将位置更改为绝对时,画布精灵表和触摸事件不起作用
- 引导程序弹出窗口(bootbox)中的Javascript事件不起作用
- 在Javascript中动态添加列时,单击事件不起作用
- 敲除数据绑定=“;html:html,内部html点击事件不起作用
- 当元素在事件绑定后附加到DOM时,触摸事件不起作用