无法获取HTML ANCHOR +如何覆盖.onclick of anchor [duplicate]

问题描述 投票:3回答:2

这个问题在这里已有答案:

在我的index.html中,我有2个锚点。我想在第一次单击它们时自定义它们的行为,之后,在发生另一次单击时更改它们的行为。

var anchors = document.querySelectorAll('a');
for (var i = 0; i < anchors.length; ++i)
  alert(anchors[i]);
<section>
  <a href='pag1'>anchor 1</a>
</section>

<section id='2'>
  <a href='pag2'>anchor 2</a>
</section>

但是当我这样做时,我得到的警报是href的完整路径:C:\ Users ... \ html \ pag1;为什么不返回HTML Anchor对象?

如果我这样做,但与<p></p>它的工作原理。它返回一个Paragraph对象。

我使用Chrome作为浏览器(也许它与此有关?)

我继续更改锚点[i] .onclick到一个函数,但似乎当我点击锚点时函数启动并在它之后,锚点仍然将我发送到href页面?如何覆盖此行为?

后来编辑:

有人向我解释过,这种行为是由锚类型对象的.toString()引起的。

问题仍然存在,如何强制锚点,以便它不会将我发送到另一个页面。

javascript html css
2个回答
2
投票

原因是当你调用Javascript的警报功能时。它将使用toString()函数将您传递给的字符串转换为字符串。

实现toString()函数以将锚对象转换为其href属性。


为了防止锚的行为:

var anchors = document.querySelectorAll('a');
for (var i = 0; i < anchors.length; ++i){
  anchors[i].onclick = function(){
    // Put your code here.

    return false;
  };
}
<section>
  <a href='pag1'>anchor 1</a>
</section>

<section id='2'>
  <a href='pag2'>anchor 2</a>
</section>

1
投票

使用addEventListener()来阻止clicka上的e.preventDefault()的默认行为。请尝试以下方法:

var anchors = document.querySelectorAll('a');

anchors.forEach(function(a){
    console.log(a);
    a.addEventListener("click",function(e){
      e.preventDefault();
  });
});
<section>
    <a href='pag1'>anchor 1</a>
</section>

<section id='2'>
    <a href='pag2'>anchor 2</a>
</section>
© www.soinside.com 2019 - 2024. All rights reserved.