Reputation: 1532
I have a problem with unwanted multiple calling function, after load dynamic content.
HTML
<div class="wrap">
<a href="javascript:;" class="addNewImage">add new image</a><br /><br /><br />
<div id="fancyDIV">
<a tabindex="1" rel="group" href="#" class="fancyLink" title="title 01"><img src="http://www.picssel.com/playground/jquery/images/01t.jpg" alt="t1" /><span>number1</span></a>
<a tabindex="1" rel="group" href="#" class="fancyLink" title="title 02"><img src="http://www.picssel.com/playground/jquery/images/02t.jpg" alt="t1" /><span>number2</span></a>
</div>
</div>
JS
$("#fancyDIV").on("focusin", function(){
$('span').on('click', function(e) {
alert(0);
});
}); // on
var $indice = 3;
$("a.addNewImage").click(function(){
if ($indice > 8) {
alert('sorry, there are no more images to add'); return false;
}else{
$("#fancyDIV").append('<a tabindex="1" rel="group" href="#" class="fancyLink"><img src="http://www.picssel.com/playground/jquery/images/0'+$indice+'t.jpg" alt="thumb'+$indice+'" /><span>number'+$indice+'</span></a>');
$indice++;
}
});
If immediately after loading I click on the span, the alert appears only 1 time, correctly.
If I add dynamically more pictures, then if I click on the last span, it also executes once, that is correct.
But if I add more dynamic pictures and I click on any of the previous span, this alert appears to me several times. This can not be, because ultimately at this point instead of an alert, send ajax request. And sends me dozens of the same queries.
I wish this alert just showed up only once, regardless of how much I will add new pictures. Can it be do?
Edit (what i want): I want to dynamically load the component and be able to click on it to sent a request ajax.Normally, this will work only for those items that are loaded at the beginning, for those added dynamically do not work.I was able to do this, by focusIn, but by then, ajax request is sent as many times as I click to add a new item. But I want to send request only once.
Upvotes: 0
Views: 716
Reputation: 3444
You never want to have nested calls to .on
like that. If you delete the outer one, the $("#fancyDIV")
, then that's almost the right way to do it.
The reason this doesn't quite work is that the handler is set before the elements are created. This means the handler is not set on those elements.
There are two ways round this. You could add the handler to the new elements when they are created. Personally I'd prefer the other way, which is to add the handler to some ancestor element, but set it to run on descendants matching a certain CSS selector. (This uses the so-called "bubble-up" feature of DOM event handling.) Like this:
$('#fancyDiv').on('click', 'span', function(e) {
alert(0);
});
This will run the handler when any <span>
element inside the #fancyDiv
is clicked.
Incidentally, it might be wise to use CSS classes or something, since there's a risk that more <span>
elements might be added to the code later.
Upvotes: 1