Reputation: 10407
<script type="text/javascript">
$(function(){
$('button').each(function(i){
$(this).click(function(){
$(this).after('<br /><button type="button">Button</button>');
});
});
});
</script>
<button type="button">Button</button>
If i click the button it works and adds a button after it. I can keep clicking the same button and adding more buttons. But if I click any of the buttons that have been added they don't add anything. I tried changing to:
$(function(){
function update(){
$('button').each(function(i){
$(this).click(function(){
$(this).after('<br /><button type="button">Button</button>');
update();
});
});
};
update();
});
But this selects the first button twice so if i press it once it works and so does the button it adds but if i press the first button a second time it adds 2 more buttons and then 4 more etc..
Upvotes: 0
Views: 280
Reputation: 37719
You can use the live method to attach event handlers to all current and future elements:
Upvotes: 1
Reputation: 45525
You need .live()
or .delegate()
, since your code binds only those elements that are in the DOM at the point/time of execution, and you're looking for all buttons, even those that do not exist yet.
For example (http://jsfiddle.net/5RWrW/):
$(function(){
$('button').live('click', function(){
$(this).after('<br /><button type="button">Button</button>');
});
});
Alternatively, you could create the new element and add a new/separate event listener, although that seems harder and more wasteful.
Upvotes: 2
Reputation: 33954
The jQuery .live() function takes care of this of this for you. It allows you to add events to all current and future elements that match the class you specify.
Upvotes: 2
Reputation: 86872
You should try using jQuery delegate() or jQuery live(). I would suggest delegate first.
Upvotes: 2
Reputation: 322492
Use event delegation to manage the click events.
$('body').delegate('button','click',function() {
$(this).after('<br /><button type="button">Button</button>');
});
This uses the delegate()
[docs] method to handle all clicks that take place in the <body>
and are preformed on elements matching the 'button'
selector.
Try it out: http://jsfiddle.net/Krrae/
If all your buttons are in a common container (other than <body>
), then use that for the delegate instead:
$('#some_button_container').delegate('button','click',function() {
$(this).after('<br /><button type="button">Button</button>');
});
Upvotes: 6