2011-10-31 33 views
0

如何使用JavaScript函數將href屬性傳遞給每個錨標記?Javascript將一個函數傳遞給每個錨標記

<a href="www.facebook.com" onclick="myurl(href)"> facebook</a><br> 
<a href="www.youtube.com" onclick="myurl(href)">youtube </a><br> 
<a href="www.google.com" onclick="myurl(href)">google </a><br> 

<script> 


function myurl(href){ 

alert(href); 
} 

</script> 

回答

3

只需使用this.href

this引用了引發該事件的DOM元素。

1
<a href="www.facebook.com" onclick="myurl(this.href)"> facebook</a><br> 
<a href="www.youtube.com" onclick="myurl(this.href)">youtube </a><br> 
<a href="www.google.com" onclick="myurl(this.href)">google </a><br> 
0

您應相應地更改代碼:

<a href="www.facebook.com" onclick="myurl(this)"> facebook</a><br> 
<a href="www.youtube.com" onclick="myurl(this)">youtube </a><br> 
<a href="www.google.com" onclick="myurl(this)">google </a><br> 
<script> 
    function myurl(el){ 
     alert(el.href); 
    } 
</script> 
0

把對象傳遞給JavaScript第一

<a href="somesite.html" onclick="myurl(this)"> somebook </a> 

然後在你的函數來完成。

function myurl(LinkObject) { alert(LinkObject.href); } 
0

你剛纔提到你想alert的所有鏈接。爲什麼你必須在你的每個錨標籤上給onclick="myurl(this)"。如果你對所有的錨標籤都有相同的功能。你可以考慮使用這個:

var elements = document.getElementsByTagName("a"); 
for(var i = 0; i < elements.length; i++) { 
    elements[i].onclick = function() { 
     alert(this.href); 
    } 
} 
相關問題