单个元素上的 die()
我附加了一些 live() 监听器,以便自动对 url 中带有 ajax 的每个链接进行 ajax 调用:
$("document").ready(function() {
$('a[href^="/ajax"]').live('click', call);
});
function call(e, context, link) {
e && e.preventDefault();
link = link || this;
if(typeof link == "string" || !$(link).hasClass("disabled")) {
newObj(SPZ.AjaxCall, link, context);
}
};
但有时我想覆盖它(以便我可以指定一个上下文来查找回调函数),所以我编写了一个 jQuery 方法来执行此操作
$.fn.customAjax = function(context) {
return this.die().click(function(e){
call.call(this, e, context);
});
};
$(".save").customAjax(myObj);
我遇到的问题是,如果将实时处理程序添加到元素集合中,我不能只对其中一个元素使用 die() ; die() 似乎只有在将其应用于所有使用 live() 的元素时才有效。
任何人都可以建议一种解决方法来抑制 live() 事件吗?顺便说一句,人们对建议 jQuery 团队更改 die() 的行为有何看法,以便可以使用它来删除单个元素上的 live() 处理程序?有什么理由说明这是一个坏主意吗?
I've attached some live() listeners in order to automatically make ajax calls for every link with ajax in the url:
$("document").ready(function() {
$('a[href^="/ajax"]').live('click', call);
});
function call(e, context, link) {
e && e.preventDefault();
link = link || this;
if(typeof link == "string" || !$(link).hasClass("disabled")) {
newObj(SPZ.AjaxCall, link, context);
}
};
But sometimes I want to override this (so that I can specify a context in which to find callback functions), so I wrote a jQuery method to do this
$.fn.customAjax = function(context) {
return this.die().click(function(e){
call.call(this, e, context);
});
};
$(".save").customAjax(myObj);
The problem I have is that if the live handler is added to a collection of elements I can't just use die() on one of those elements; die() only works, it seems, if you apply it to all the elements live() was used on.
Can anyone suggest a workaround that will suppress the live() event? And, as an aside, what are people's opinions on suggesting the jQuery team change the behaviour of die() so that it can be used to remove live() handlers on individual elements; are there any reasons why this would be a bad idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
call
从哪里来?我没有看到它在此代码部分的某处定义。<罢工>
除此之外,我认为你的
this
并不是指一个 jQuery 对象,而是一个 DOM 节点。尝试包裹它:Where does
call
come from? I do not see it defined somewhere in this code section.Besides that, i think your
this
does not refer to a jQuery object, but a DOM node. Try wrapping it:多玩一会儿,我发现在 jQuery 方法末尾添加一个简单的 return false 就可以了。如果我想为同一次点击附加其他侦听器,这会导致问题,但现在就可以了。
A bit more playing around and I found that adding a simple return false at the end of my jQuery method did the trick. It'll cause problems if I ever want to attach other listeners for the same click, but it'll do for now.