2014-01-11 64 views
0

我正在動態創建多個錨標記。我想要在javascript中獲取單擊的錨標記的href值。我使用下面的代碼來做到這一點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我得到的第一錨tag.I的價值就在想它會得到價值被點擊的元素。

是否有任何其他方式可以從標籤獲取多個動態生成的href值。

function follow(item) { 

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

ID是一個獨特的價值。你不能有幾個元素具有相同的ID – Curious

+1

我認爲向我們展示'follow()'函數的定義是有意義的。 – JLRishe

+1

順便說一句,你應該避免空間中的href ... – Merlin

回答

3

試試這個代碼:

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

UPDATE

但你必須禁用本地連接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); 
} 

而且你不必在所有

更新2

使用id屬性全碼:

<!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> 
+0

警報顯示文本爲undefined而不是href值 –

+0

@ManishSingh您使用的是哪種瀏覽器?我在Ubuntu上,不能在IE中測試它,不幸的是 – Curious

+0

我正在使用Chrome和IE瀏覽器。 –

0

ID必須是唯一的。設置一個不同的ID到每個<a>標籤

<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