[英]multiple anchor tag href value in javascript
我正在动态创建多个锚定标记。我想在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我都将获得第一个锚标记的价值。我以为它将获得clicked元素的价值。
还有什么其他方法可以从标记中获取href的多个动态生成的值。
function follow(item) {
href=document.getElementById("aaa").href;
document.writeln(href);
}
试试这个代码:
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>
ID必须是唯一的。 为每个<a>
标签设置一个不同的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.