Reputation: 139
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.
Upvotes: 1
Views: 204
Reputation: 26380
<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/
Upvotes: 3