开发者

Progressive enhancement of anchor tags to avoid onclick="return false;"

Unobtrusive JS suggests that we don't have any onclick attributes in our HTML templates.

<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.

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.

To avoid the cost of 2 event listeners, I could shove my function call into the onclick attribute

<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?

onclick="return false;"

Manipulating the href is not an option. It must stay 开发者_Go百科intact so the context menu options to copy or open in new page work as expected.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜