index.php
<button class="cat" data-table="cat" >Cat</button>
<div class="animals"></div>
script.js:
$(document).on("click", ".cat", function (event) {
alert("cat");
var table = $(this).data('table');
$.ajax({
url: "update.php",
data: {
table: table,
},
type: "POST",
success: function (data) {
$(".animals").html(data);
}
})
});
$(document).on("click", ".dog", function (event) {
alert("dog");
var table = $(this).data('table');
$.ajax({
url: "update.php",
data: {
table: table,
},
type: "POST",
success: function (data) {
$(".animals").html(data);
}
})
});
$(document).on("click", ".bird", function (event) {
alert("bird");
var table = $(this).data('table');
$.ajax({
url: "update.php",
data: {
table: table,
},
type: "POST",
success: function (data) {
$(".animals").html(data);
}
})
});
update.php
if ($table == "cat") {
echo "<button class='dog' data-table='dog'>Dog</button>";
}
if ($table == "dog") {
echo "<button class='dog' data-table='dog'>Dog</button><button class='bird' data-table='bird'>bird</button>";
}
if ($table == "bird") {
echo "nothing";
}
通过单击动物按钮(例如"鸟"(,我希望警报盒火只有一次。但是,每当我单击动物时,警报框都会发射越来越多的次。
尝试一下..'Unbrind'
$('#updateUser').unbind('click').click(function () {
//do here ..
})
更改您的点击事件。使用"一个"而不是" on"。引用jQuery文档,它将仅执行一次点击事件。请参阅下面的示例
$(document).one("click","#btn1",function(){
alert("button btn1 clicked");
});
$(document).on("click","#btn2",function(){
alert("button btn2 clicked");
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js">
</script>
<button id="btn1">Click me(Executes once)</button>
<button id="btn2">Click me(Executes multiple times)</button>
尝试以这种方式。
$('#do-something').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "<url>",
data: $("#form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
在.on((之前尝试.off((,如下:
$(document).off().on("click", ".dog", function (event) {
alert("dog");
var table = $(this).data('table');
$.ajax({
url: "update.php",
data: {
table: table,
},
type: "POST",
success: function (data) {
$(".animals").html(data);
}
})
});
而不是.on
您可以使用jQuery的.one
。