gil*_*ero 18 javascript jquery
我想为稍后在DOM中创建的元素添加事件句柄.
基本上,我想要做的是,当我点击时p#one,p#two将创建新元素,然后我点击p#two,告诉我"p#two"点击.但是,它不起作用,我console.log点击后没有得到'p#two clicked' 的结果p#two.
我on()用来添加点击事件p#two.我做错了什么?
谢谢.
以下是我的示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>on() test</title>
<link type="text/css" href="http://localhost/jquery-ui-1.8.20.custom/css/smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" />
<script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('p#two').on('click', function() {
console.log('p#two clicked');
});
$('p#one').click(function() {
console.log('p#one clicked');
$('<p id="two">two</p>').insertAfter('p#one');
});
}); // end doc ready
</script>
</head>
<body>
<p id="one">one</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
the*_*dox 28
$('body').on('click','p#two', function() {
console.log('p#two clicked');
});
Run Code Online (Sandbox Code Playgroud)
你也可以用
$(document).on('click', 'p#two', function() {
});
Run Code Online (Sandbox Code Playgroud)
了解更多 .on()
你也可以用 .delegate()
$('body').delegate('#two', 'click', function() {
});
Run Code Online (Sandbox Code Playgroud)
Pra*_*Nag 12
您可以将$ .on绑定到将始终存在于dom中的父元素.
$(document).on('click','p#two', function() {
console.log('p#two clicked');
});
Run Code Online (Sandbox Code Playgroud)
请注意:您可以替换document为dom中始终存在的元素的任何父元素,并且父元素越接近越好.
检查$ .on的文档
实时折旧.请改用$ .on.$ .on的等价语法为$ .live和$ .delegate
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Run Code Online (Sandbox Code Playgroud)
我建议你$.on用于所有事件处理目的,因为所有其他方法都通过$ .on方法引导.
从jQuery源v.1.7.2检查这些函数的定义
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
}
Run Code Online (Sandbox Code Playgroud)
您可以看到所有方法都在使用$.on和$.off自己.所以使用$.on你至少可以保存一个函数调用,虽然大多数情况并不是那么重要.