覆盖 Javascript 中链接 ('a') 对象的默认行为 [英] Override default behaviour for link ('a') objects in Javascript

查看:24
本文介绍了覆盖 Javascript 中链接 ('a') 对象的默认行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根本不知道我想要完成的事情是否可行.我想覆盖给定 HTML 页面的所有锚对象(A 标记)的默认行为.我知道我可以遍历所有的 A 元素,并从 body 元素的 onload 方法动态添加一个 onclick 调用到每个元素,但是我正在寻找更绝对的解决方案.我需要的是为所有 A 元素分配一个 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
  }
};

这里检查上面的例子.

这篇关于覆盖 Javascript 中链接 ('a') 对象的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆