first of all, I did my home work, I already searched Google and used evt.stopPropagation(); and unbind method, but not fixing my problem... .
Here is my case:
Imagine I have a left sidebdar with some linkes, on click of each link the middle col will be reloaded by ajax with some code like this:
<script>
$('.leftsidebar a').on('click', function(){
var page = $(this).attr('class')
$('#middleCol').load('loader.php?page='+ page);
});
</script>
So on each click on the left side bar a tag, the middle col will loads that a tag class.php, it's just fine.
now in the pages that I'm loading in the middle col, at the end of the page I have some javascripts,, for example if it loads by loader.php?page=test in test page I have some new jQuery lines, an example:
<script>
$('#blah').on('click', function(){
$.ajax({
type: 'POST',
url: 'server.php',
success: function(response){
//blah
}
});
});
</script>
Now the problem is, when the first time, I load test page by clicking on leftside bar a tag, it works just fine, on click of #blah only 1 request will be sent to server.php, but when I click on another a from leftsidebar, then come back to the test, now if I click on blah, the ajax request will be sent twice to the server.php, and so on..., if I try it again, request will be sent for 3 times!
How can I prevent such behavior? what is the solution?
I appreciate helps.
You could do that too if no more than one click handler is bounded to this element:
$('#blah').off('click').on('click', function(){...});
But better would be to not include useless/redundant code
A fairly simple solution would be to bind data to #blah to determine whether that click event is already bound to prevent it from binding again.
$("#blah:not([data-bound])").on('click', function () {
/* your code */
});
//not using .data to ensure attribute string set for selector use.
$("#blah").attr('data-bound', 'bound');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With