【问题标题】:multiple anchor tag href value in javascriptjavascript中的多个锚标记href值
【发布时间】:2014-01-11 14:13:59
【问题描述】:

我正在动态创建多个锚标记。我想在 javascript 中获取单击的锚标记的 href 值。我正在使用以下代码来做到这一点

javascript

document.getElementById("aaa").href

<a id="aaa" onclick="follow(this);" href="sec/IF   00.html">Hi</a>
<a id="aaa" onclick="follow(this);" href="sec/IF   002.html">Hi</a>

但是每次当我点击锚标记时,通过 javascript 我得到第一个锚标记的值。我在想它会得到点击元素的值。

有没有其他方法可以从标签中获取多个动态生成的href值。

   function follow(item) {

           href=document.getElementById("aaa").href;
           document.writeln(href);
}

【问题讨论】:

  • ID 是唯一值。不能有多个具有相同 ID 的元素
  • 我认为向我们展示您的 follow() 函数的定义是有意义的。
  • 顺便说一句,您应该避免在 href 中使用空格...
  • 首先要提醒您的是,有些事情不太正确,您将元素作为item 传递给您的follow() 函数,然后根本不使用item

标签: javascript jsp


【解决方案1】:

试试这个代码:

function follow(item) {
    alert(item.href);
}

更新

但是你必须禁用原生链接click触发:

html:

<a onclick="follow(event, this);" href="sec/IF00.html">Hi</a>

javascript:

function follow(e, item) {
    e = e || window.event;  //IE stuff
    e.preventDefault();     //prevent link click triggering
    e.returnValue = false;  //also prevent link click triggering (old IE style)
    alert(item.href);
}

而且你根本不必使用id 属性

更新 2

完整代码:

<!DOCTYPE html>
<html>
<head>
<script>
function follow(e, item) {
    e = e || window.event;  //IE stuff
    e.preventDefault();     //prevent link click triggering
    e.returnValue = false;  //also prevent link click triggering (old IE style)
    alert(item.getAttribute('href'));
}
</script>
</head>
<body>

<a onclick="follow(event, this);" href="sec/IF00.html">Hi</a>
<a onclick="follow(event, this);" href="sec/IF002.html">Hi</a>

</body>
</html>

【讨论】:

  • @ManishSingh 你用的是什么浏览器?我在 Ubuntu 上,不幸的是无法在 IE 中测试它
  • 我同时使用 chrome 和 IE。
  • @ManishSingh 请尝试使用item.getAttribute('href') 而不是item.href
  • 更新了帖子 - 现在你可以看到完整的代码,在 Ubuntu Chrome 中工作
  • 我再次测试了这段代码,我从localhost:8081/sec/IF00.html得到了完整的url,谢谢你的帮助,这就是我一直在寻找的没有id的工作。
【解决方案2】:

ID 必须是唯一的。为每个&lt;a&gt;标签设置不同的id

<a id="aaa" onclick="follow(this);" href="sec/IF00.html">Hi</a>
<a id="bbb" onclick="follow(this);" href="sec/IF002.html">Hi</a>

document.getElementById("aaa").href  // sec/IF00.html
document.getElementById("bbb").href  // sec/IF002.html

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 2011-04-29
    • 2012-06-08
    • 2011-04-08
    • 1970-01-01
    • 2015-09-23
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多