解除绑定特定的 jquery 元素
假设我想通过特殊函数处理页面上的所有链接,所以我这样做:
$('a').bind("click", handleLinks);
但是我有一个导航栏,其中包含我想要以不同方式处理的链接。 所以我想这样做,但这不起作用:
$('#navbar a').unbind("click", handleLinks);
我不想在第一个语句中专门排除导航栏,因为内容是动态加载的,所以我需要监视点击的元素将根据内容而变化。 基本上,我希望能够从最初绑定的较大初始元素子集动态地解除绑定特定的元素子集。
有什么建议么?
:: 更新 ::
我真诚地道歉,你们都是对的 - 调用命令的顺序有些奇怪。 对不起!
Let's say I want to handle all links on a page, via a special function, so I do:
$('a').bind("click", handleLinks);
But I have a navbar with links that I want to handle differently. So I want to do this, which does not work:
$('#navbar a').unbind("click", handleLinks);
I do not want to specifically exclude the navbar in the first statement, because content is loaded dynamically, so the elements I need to monitor for clicks will change depending on the content. Basically I want to be able to unbind specific subsets of elements dynamically, from the larger initial subset of elements that was bound initially.
Any suggestions?
:: UPDATE ::
My sincere apologies, you're all correct - there was something funky with the order the commands were being called. Sorry!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我同意 apocalypse9 的观点,你所拥有的似乎应该有效。 也许不同的方法会有更好的结果...如何将 :not 选择器与 live() 一起使用。 Live 将确保选择器适用于动态添加的元素。
http://docs.jquery.com/Selectors/not#selector
http://docs.jquery.com/Events/live
I agree with apocalypse9 that it seems like what you have should work. Perhaps a different approach would have better results... How about using the :not selector with live(). Live will ensure the selector works with dynamically added elements.
http://docs.jquery.com/Selectors/not#selector
http://docs.jquery.com/Events/live
奇怪——看起来是正确的。 您是否测试过您的初始声明正在选择您认为它的作用?
http://docs.jquery.com/Events/unbind
编辑 -
好吧,我做了一个测试页,
这工作得很好,但是如果我内联构建了我的函数,我需要从选择元素中取消绑定所有事件以将其删除。 不确定这是否适用,但值得一提。
你介意多发布一点代码吗> 看起来可能还有其他问题。
Strange- that looks correct. Have you tested that your initial statement is selecting what you think it does?
http://docs.jquery.com/Events/unbind
edit-
Ok I did a test page
This works fine, however if I built my function inline I needed to unbind all events from select elements to remove it. Not sure if that applies or not but worth mentioning.
Do you mind posting a bit more code> it looks like there may be something else wrong.