On my site I have multiple buttons and every button is loaded on the site twice through ajax from the same file.
Though my problem is that this event fires twice if the same button is loaded twice. Though it works fine if only one of the buttons is loaded.
My code:
index.php
<div id="firstButtonContainer">
</div>
<div id="secondButtonContainer">
</div>
<script>
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
script.onload = function(){
$.ajax({
url: '/test/firstButtonContainer.php',
success: function(msg) {
jQuery('#firstButtonContainer').html(msg);
}
});
$.ajax({
url: '/test/secondButtonContainer.php',
success: function(msg) {
jQuery('#secondButtonContainer').html(msg);
}
});
};document.body.appendChild(script);
</script>
buttons.php
<button class="testbutton">Button1</button>
<button class="testbutton">Button2</button>
<button class="testbutton">Button3</button>
<button class="testbutton">Button4</button>
<script>
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
script.onload = function(){
$(".testbutton").on("click", function(event){
alert("this should only appear once");
});
};document.body.appendChild(script);
</script>
firstButtonContainer.php
<div id="buttons">
</div>
<script>
$.ajax({
url: '/test/buttons.php',
success: function(msg) {
jQuery('#buttons').html(msg);
}
});
</script>
secondButtonContainer.php
<div id="buttonsTwo">
</div>
<script>
$.ajax({
url: '/test/buttons.php',
success: function(msg) {
jQuery('#buttonsTwo').html(msg);
}
});
</script>