简体   繁体   中英

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

I want to add an event handle to an element that will be created later in DOM.

Basically, what I am trying to do is that, when I click p#one , new element p#two will be created, then I click p#two , tell me "p#two" clicked. However, it doesn't work, I didn't get the console.log result of 'p#two clicked' after I click p#two .

I use on() to add click event to p#two . What do I do wrong?

Thanks.

Below is my example code:

<!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');
});

you can also use

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

});

Read more about .on()

you can also use .delegate()

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

});

You can bind the $.on to a parent element that will always exist in dom like this.

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

Note that: you can replace document with any parent of the element that will always exist in dom, and the closer the parent the better.

Check doc of $.on

Live is depreciated. use $.on instead. Equivalent syntax of $.on for $.live and $.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+

I would suggest you to use $.on for all event handling purposes as all other methods routes through $.on method under the hood.

Check the definition of these functions from jQuery source 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 );
} 

You can see all methods are using $.on and $.off themselves. So using $.on you can at least save a function call though which isn't that significant most of the cases.

You want to use Jquery.on

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM