如何在页面上的所有超链接上调用函数

How do I call a function on all hyperlinks on my page?

本文关键字:超链接 调用 函数      更新时间:2023-09-26

我有一个包含多个超链接的网页。 他们都有一个"#"的href。 它们是动态生成的。单击其中任何一个时如何调用函数?我希望保留默认的超链接操作。

使用事件委派

window.onload = function () {
  document.body.onclick = function (e) {
    var target = e.target,  
        isLink = target.tagName.toLowerCase() === 'a';
    if (isLink && target.getAttribute('href') === '#') {
      lickFun(e); 
    }
  };
  function lickFun(e) {
      console.log('this is link');
      console.log('href equals #');         
  }
}

Example

这可以很容易地在普通的 JavaScript 中完成。 方法如下。

  1. 使用document.querySelectorAll("a[href='#']选择href为" # "的所有链接。

  2. 使用 for 循环遍历所有链接。

  3. 向所有链接添加事件侦听器。 就像这样(此代码段包括动态生成的链接):

document.body.innerHTML = '<a href="#">Click me to call a function.</a><br/>' +
'<a href="#">Click me to call the same function.<'/a><br/>' +
'<a href="#">Click me to call the same function.<'/a><br/>' +
'<a href="#">Click me to call the same function.<'/a><br/>' +
'<a href="#">Click me to call the same function.<'/a><br/>' +
'<a href="http://www.cnn.com">My "href" is not "#".<'/a><br/>' +
'<a href="http://espn.go.com">Neither is mine.<'/a>'
var linkListener = document.querySelectorAll("a[href='#']");
for (i=0;i<linkListener.length;i++){
  linkListener[i].addEventListener("click", linkFunction);
  }
function linkFunction(){
  
  alert("You clicked a link with an '"href'" of '"#'".");
  
  }

单击任何href为" #"的链接将调用linkFunction

如果你使用的是jquery,你可以这样做:

<a href="http://google.com">google</a>
<a href="#">test1</a>
<a href="#">test2</a>
<a href="#">test3</a>
<script>
        $('a[href="#"]').bind('click',function(){
            alert("Test");
        })
</script>