Unobtrusive JS suggests that we don't have any onclick attributes in our HTML templates.
不引人注目的JS表明我们的HTML模板中没有任何onclick属性。
<a href="/controller/foo/1">View Foo 1</a>
A basic progressive enhancement is to convert that anchor tag to use XHR to retrieve a DOM fragment. So, I write JS to add an event listener for a."click" then make an XHR to a.href.
基本的渐进增强是将该锚标记转换为使用XHR来检索DOM片段。所以,我编写JS来为a。“click”添加一个事件监听器,然后将一个XHR添加到a.href。
Alas, the browser still wants to navigate to "/controller/foo". So, I write JS to dynamically inject a.onclick = "return false;". Still unobtrusive (I guess), but now I'm paying the the cost of an extra event handler.
唉,浏览器仍然希望导航到“/ controller / foo”。所以,我写JS来动态注入a.onclick =“return false;”。仍然不引人注目(我猜),但现在我付出额外的事件处理程序的成本。
To avoid the cost of 2 event listeners, I could shove my function call into the onclick attribute
为了避免2个事件监听器的成本,我可以将我的函数调用推送到onclick属性
<a href="/controller/foo/1" onclick="myXHRFcn(); return false;">
But that's grodo for all sorts of reasons.
但出于各种原因,这是一个结果。
To make it more interesting, I might have 100 anchor tags that I want to enhance. A better pattern is a single listener on a parent node that relies on event bubbling. That's cool, but how do I short circuit the browser from navigating to the URL without this on every anchor node?
为了使它更有趣,我可能有100个我想要增强的锚标签。更好的模式是父节点上依赖于事件冒泡的单个侦听器。这很酷,但是如何在每个锚节点上将浏览器从导航到URL没有这个短路?
onclick="return false;"
Manipulating the href is not an option. It must stay intact so the context menu options to copy or open in new page work as expected.
操作href不是一种选择。它必须保持不变,以便在新页面中复制或打开的上下文菜单选项按预期工作。
1 个解决方案
#1
1
event.stopPropagation()
is likely what you are looking for (inside of the event handler where you are checking the event.target
for the bubbled click)
event.stopPropagation()可能就是您要查找的内容(在事件处理程序内部,您正在检查冒泡点击的event.target)
#1
1
event.stopPropagation()
is likely what you are looking for (inside of the event handler where you are checking the event.target
for the bubbled click)
event.stopPropagation()可能就是您要查找的内容(在事件处理程序内部,您正在检查冒泡点击的event.target)