处理程序函数中的jQuery-off()和on()
我使用jQuery处理程序函数中的jQuery-off()和on(),jquery,events,Jquery,Events,我使用jQuery.on()方法将事件处理程序函数附加到id为“w1”的另一个div元素中的所有div元素,但在事件处理程序函数中,我希望在ajax调用之前分离该事件,并在ajax完成后再次附加该事件。下面是一个简单的脚本 $(document).on("click", "#w1 div", function() { $(document).off("click","#w1 div"); $.ajax({ type: "POST", cache:
.on()
方法将事件处理程序函数附加到id为“w1”的另一个div元素中的所有div元素,但在事件处理程序函数中,我希望在ajax调用之前分离该事件,并在ajax完成后再次附加该事件。下面是一个简单的脚本
$(document).on("click", "#w1 div", function() {
$(document).off("click","#w1 div");
$.ajax({
type: "POST",
cache: false,
url: "chtr.py",
complete: function(){
$(document).on("click","#w1 div"); // does not work
}
});
});
我不知道如何再次将事件处理程序函数附加到这些元素。也许您应该使用
jQuery。一个:
描述:将处理程序附加到元素的事件。这个
每个元素最多执行一次处理程序
因此,您的代码可能如下所示:
var ajaxHandling = function() {
$.ajax({
type: POST,
cache: false,
url: "chtr.py",
complete: function(){
$(document).one("click", "#w1 div", ajaxHandling);
}
});
}
$(document).one("click", "#w1 div", ajaxHandling);
如果要附加相同的函数,则需要将其设置为命名函数,以便再次引用(或者可以将其指定给变量):
最好对此使用标志:
$(document).on("click", "#w1 div", function() {
var $this = $(this);
if ($this.data('in-progress')) {
return false;
}
// set the flag to prevent furthur clicks
$this.data('in-progress', true);
$.ajax({
type: 'POST',
cache: false,
url: "chtr.py",
complete: function(){
// here ajax is completed
// set the flag back
$this.data('in-progress', false);
}
});
});
- 打开
控制台
并进行检查
很抱歉,如果你说的是显而易见的,但是在完整版中,你绑定到的是#headnav而不是#w1?在POST
中缺少的“
是一个打字错误吗?还是问题?无论如何,
上的想要第三个参数,这是绑定后要调用的函数!有一个打字错误,最后一个应该是:$(文档)。在(“单击”,“w1 div”,clickHandler)@烤熟了:是的。早上的咖啡还没有完全开始。修好了。
$(document).on("click", "#w1 div", clickHandler);
function clickHandler() {
$(document).off("click","#w1 div");
$.ajax({
type: POST,
cache: false,
url: "chtr.py",
complete: function(){
$(document).on("click","#w1 div", clickHandler);
}
});
}
$(document).on("click", "#w1 div", function() {
var $this = $(this);
if ($this.data('in-progress')) {
return false;
}
// set the flag to prevent furthur clicks
$this.data('in-progress', true);
$.ajax({
type: 'POST',
cache: false,
url: "chtr.py",
complete: function(){
// here ajax is completed
// set the flag back
$this.data('in-progress', false);
}
});
});