I have 2 html elements: A and B, here is the jquery code:
$('A').click(function(){
$('B').click(function(){
console.log("hello");
})
})
when I click A and then click B, it will show me “hello”, which is fine.
But when I click A again and then click B, this time it shows me TWO “hello”, which is undesirable. I only want ONE hello.
I more or less know the reason, it might be the result of the callback function: B is still waiting for user to click it after the first click.
now my question is: if I still want “clicking B” inside “clicking A” (“clicking B” is a callback function of “clicking A”), how can I solve the double result problem?
I am new to the callback function, please help!!!
The problem is, that each consecutive click on
Aadds another click-handler to yourB. Each of these handlers get executed when you click onB. So if you clickAten times, you have bound ten clickhandlers toB😀To avoid the problems of the other solutions, constant un- and rebinding and global variables which both are nasty, use this clean solution instead:
By using
.one()instead of click, the click-event onAis triggered only once, binding exactly one click-eventhandler to your elementB.Example Fiddle