我只是想知道jquery是否有一种方法可以在点击时拦截链接。问题是我的页面上的一些链接在第一次加载页面时没有加载。我有一个模糊的记忆,听说jquery有一种方法可以拦截所有当前和未来的链接。这是我的代码。它适用于开始时存在的所有链接,但后来加载到页面上的链接不会被此函数截获
$('a').trackClick({
areaClick: function(element) { return getAreaClicked(element); },
href: function(element) { return getHrefFromElement(element); },
text: function(element) { return getTextFromElement(element); },
exceptions: function(element) { return isException(element); }
});发布于 2014-04-25 19:50:58
如前所述,推荐.live()和.delegate()的答案是out of date。
我有一个类似的问题:我已经在各种元素上使用了各种点击处理程序,但我想添加一个额外的点击处理程序来捕获所有内容,并尽可能在其他元素之前采取行动。
我的用例是想让web-app中的各种工具在其他工具被点击时“重置”到默认状态。
这是我的解决方案。
$(document).on("click", function(e){
// This catches all clicks.
// It can be suppressed if the target uses e.stopPropagation()
});
// To start the bubbling from an element "higher" than the document,
// then use delegation, e.g.:
// $(document).on("click", ".your_class", function(e){ etc })
// This can be really useful if you only have one sensitive area in the layout,
// or you want different "master" click behaviours for different areas!
$("#my_element").on("click", function(e){
// prevent the default action, e.g. prevent "#" navigation on <a href="#">
e.preventDefault();
// prevent the click bubbling to the $(document) handler
e.stopPropagation();
// now do my stuff
// ...
});
$("#my_other_element").on("click", function(e){
// prevent the default action, e.g. prevent "#" navigation on <a href="#">
e.preventDefault();
// this time I want the "catch all" to fire
// so I don't do stopPropagation()
// now do my stuff
// ...
});https://stackoverflow.com/questions/7599300
复制相似问题