问题
I have a button. when I click it I am appending some buttons to the DOM.
The issue I have is that those buttons that I am appending fire multiple times.
$(el).on('click', function (e) {
key();
});
function key() {
$(document).on('click', '#key li', function () {
console.log($(this));
});
}
First time key()
is called, the console.log
fires once
The second time I call key()
the console.log
fires twice
And so on
I've tried adding $(document).find('#key li').unbind('click')
, but that doesn't seem to work
Any ideas?
edit:
Here is an jsfiddle example (shown below).
$('button').on('click', function () {
$('.cont').remove();
$('.container').remove();
var html = '<button class="cont">click</button><div class="container">placeholder</div>';
$('body').append(html);
key();
});
$(document).on('click', '.cont', function () {
var html = '<div id="but_placeholder"><button class="one">1</button><button class="two">2</button><button class="three">3</button></div>';
$('.container').html(html);
});
function key() {
$(document).on('click', '#but_placeholder button', function () {
$('input').val($('input').val() + $(this).html());
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" />
<button>test</button>
To reproduce, click on the test
button, then on the click
,then one 1
2
3
and repeat the process
You will notice that the second time you go through the process the text doubles
回答1:
Do this
function key() {
$('#key li').unbind('click');
$('#key li').bind('click', function () {
console.log($(this));
});
}
or you could do
function key() {
$('#key').find('li').unbind('click');
$('#key').find('li').bind('click', function () {
console.log($(this));
});
}
I guess the second one will surely work.
Updated method
function key() {
$(document).off('click', '#but_placeholder button');
$(document).on('click', '#but_placeholder button', function () {
$('input').val($('input').val() + $(this).html());
});
}
回答2:
Try to give all the buttons a unique id.
回答3:
Try setting the on
on the document, that should do it, and will only bind once, including future (generated) elements. Eg:
$(document).on('click', '#key li', function() {
//do stuff
});
The point is, you keep rebinding to the click event using the key() function. As you are binding the on
event to the document, you don't need to wrap this in a function. Binding like this (my code above) will tell jQuery to bind the action (in my case '//do stuff') to every click event on a '#key li' it finds in the document. Wether it is there or not, wether there is one or there are many. I hope this explains it somewhat.
Fiddle
In my fiddle I modified your other code somewhat, and pre-wrap the inserted buttons as a jQuery object so you do not only append a button, but already set up actions on it.
来源:https://stackoverflow.com/questions/20733638/click-event-fires-multiple-times-issue-how-to