在我的网站上,我有多个按钮,每个按钮都通过 ajax 从同一个文件加载到网站上两次。
虽然我的问题是如果同一个按钮被加载两次,这个事件会触发两次。虽然如果只加载一个按钮,它就可以正常工作。
我的代码:
索引.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>
按钮.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>