Suppose I have this:
<div id='container'>
</div>
<input type='button' id='newTest' value='new' />
And some JQuery/JavaScript:
$('#newTest').click( function() {
var newDiv = "<div class='test'>Click Me</div>";
$('#container').append(newDiv);
apply_click();
});
function apply_click() {
$('.test').click( function() {
alert('clicked');
});
}
Each new 'test' div that gets created should alert when clicked on... but each time we create a new 'test' div the .click function is applied to all of them again which means if I click the 'new' button 3 times and then click the first 'Click Me' div, 3 'clicked' alerts pop in sequence... The question is then: how can I cause the apply_click() function to only apply to elements it has not already been applied to...?
I'm thinking there may be a way to do it if I have apply_click() accept an argument that is a reference to the newly created element but I'm not sure how that would work.
CodePen: http://codepen.io/anon/pen/rGcwx
You're attaching a click event to everything selected by $('.test')
each time you create a new element, which is every element that has that class, including those you've already appended.
Why not use event delegation, which will allow you to bind a single event handler once?
$('#container').on('click', '.test', function(e){ ... });
All clicks on .test
elements will bubble up to #container
and you can handle them there.
The way you have it set up is that every time you create a new element, a new click handler is applied to all .test
elements. Pass the specific element into the apply_click()
function so that it applies only to the new div.
$('#newTest').click( function() {
var newDiv = $("<div class='test'>Click Me</div>");
$('#container').append(newDiv);
apply_click(newDiv);
});
function apply_click(element) {
$(element).click( function() {
alert('clicked');
});
}
Create a new jQuery object, then after appending it, then bind the click to that object, not the entire class.
$('#newTest').click(function () {
var newDiv = $("<div class='test'>Click Me</div>");
$('#container').append(newDiv);
newDiv.click(apply_click)
});
function apply_click() {
alert('clicked');
}
Change your code to use the one method:
$('#newTest').one("click", function() { var newDiv = "<div class='test'>Click Me</div>"; $('#container').append(newDiv); apply_click(); });
The .one() method is identical to .on(), except that the handler is unbound after its first invocation. http://api.jquery.com/one/
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.