简体   繁体   中英

jQuery .on delegate not working

I created a simple code but it seems that the .on delegation does not work? Please help?

HTML:

<input type="button" value="Click Me!" id="button0" class=".button" />
<br/><input type="button" value="Add" id="add_button" />
<script>
    var idx = 1;
    $(document).ready(function(){
        $(document.body).on('click',".button",function(){
            alert(this.id);
        });
        $('#add_button').on('click',function(){
            $('<input type="button" value="Click Me!" class=".button" />')
                .attr('id','button' + idx++)
                .insertBefore($(this).prev());
        });
    });
</script>

The "Click Me!" button should alert the ID attribute of the button, while the add button should add another "Click Me!" button with a different ID attribute value. http://jsfiddle.net/SrwrK/

Please take note that I am trying to have a workaround with the .live() method of jQuery since it has been deprecated and removed from 1.9.

<input type="button" value="Click Me!" id="button0" class=".button" />

This code is incorrect - remove the "." from in front of the button class. Classnames only get the "." in CSS selectors like in a CSS file or in a jQuery selector statement.

<input type="button" value="Click Me!" id="button0" class="button" />

This will work. The button you generate with jQuery has the same problem, so make it look like this:

$('<input type="button" value="Click Me!" class="button" />')

You could even simplify it a bit more like this:

$('<input type="button" value="Click Me!" class="button" id="button' + idx++ + '" />')

That will let you skip the .attr() method.

Here's a working JSfiddle: http://jsfiddle.net/SrwrK/1/

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