使用 on() 将事件处理程序添加到尚不存在的元素

Add event handler to an element that not yet exists using on()?

本文关键字:不存在 元素 添加 程序 on 事件处理 使用      更新时间:2023-09-26

我想向稍后将在DOM中创建的元素添加一个事件句柄。

基本上,我要做的是,当我单击p#one时,将创建新元素p#two,然后单击p#two,告诉我单击"p#two"。但是,它不起作用,单击p#two后,我没有得到" p#two单击"的console.log结果。

我使用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>
$('body').on('click','p#two', function() {
    console.log('p#two clicked');
});

您也可以使用

$(document).on('click', 'p#two', function() {
});

阅读更多 关于 .on()

您也可以使用.delegate()

$('body').delegate('#two', 'click', function() {
});

您可以将 $.on 绑定到一个父元素,该父元素将始终存在于 dom 中,如下所示。

$(document).on('click','p#two', function() {
            console.log('p#two clicked');
        });

请注意:您可以将 document 替换为始终存在于 dom 中的元素的任何父元素,父级越接近越好。

检查文档 $.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+

我建议您$.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 );
} 

您可以看到所有方法都在使用$.on$.off本身。因此,使用 $.on您至少可以保存函数调用,尽管在大多数情况下这不是那么重要。

你想使用 Jquery.on

$('body').on('click','p#two', function() {
        console.log('p#two clicked');
    });