覆盖Javascript中链接('a')对象的默认行为 [英] Override default behaviour for link ('a') objects in Javascript
问题描述
我不知道我想要完成什么是可能的。我想覆盖给定HTML页面的所有锚对象( A
标记)的默认行为。我知道我可以循环遍历所有 A
元素,并从身体动态添加一个 onclick
调用它们中的每一个元素 onload
方法,但我正在寻找一个更绝对的解决方案。我需要的是,所有元素被赋予一个
onclick
动作,它调用传递元素 href
属性作为参数,因此如下:
I don't know if what I'm trying to accomplish is possible at all. I would like to override the default behaviour for all the anchor objects (A
tag) for a given HTML page. I know I can loop through all the A
elements and dynamically add an onclick
call to each one of them from the body element onload
method, but I'm looking for a more absolute solution. What I need is that all A
elements get assigned an onclick
action which calls a method that passes the element href
property as an argument, so the following:
<a href="http://domain.tld/page.html">
动态变为:
<a href="http://domain.tld/page.html" onclick="someMethodName('http://domain.tld/page.html'); return false;">
像我说的,这样做的理想方法是以某种方式覆盖Anchor类,当文档加载如果不可能,我将诉诸于循环遍历的所有 A
元素方法(我已经知道如何做)。
Like I said, the ideal way to do this would be to somehow override the Anchor class altogether when the document loads. If it's not possible then I'll resort to the loop-through-all A
elements method (which I already know how to do).
推荐答案
如果您不想迭代所有的锚点元素,可以使用事件委托,例如:
If you don't want to iterate over all your anchor elements, you can simply use event delegation, for example:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
someFunction(element.href);
return false; // prevent default action and stop event propagation
}
};
检查上面的例子 here 。
这篇关于覆盖Javascript中链接('a')对象的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!