2015-09-16 132 views
0

我多張元素具有相同ID的多個元素得到名稱

<a href='#' id='Favorites[]' name='Favorites1'>1</a> 
<a href='#' id='Favorites[]' name='Favorites2'>2</a> 
<a href='#' id='Favorites[]' name='Favorites..'>..</a> 
<a href='#' id='Favorites[]' name='Favorites1000'>1000</a> 

I trying to get name of clicked element

$("#Favorites").on('click', function() { 
    alert(this.name); 
}); 

但它僅適用於第一要素,其他要素不是點擊事件作出反應

如何修復?

回答

3

id應該是唯一的,所以你需要使用class代替,否則只會選擇與id

$(".Favorites").on('click', function() { 
 
    alert(this.name); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href='#' class='Favorites' name='Favorites1'>1</a> 
 
<a href='#' class='Favorites' name='Favorites2'>2</a> 
 
<a href='#' class='Favorites' name='Favorites..'>3</a> 
 
<a href='#' class='Favorites' name='Favorites1000'>4</a>

1

第一DOM元素我認爲這個問題是jQuery的選擇器#Favourites僅用於查找具有該值的單個「id」,以便忽略其他值。

你可以考慮將「收藏夾」到是象類:

<a href='#' class='Favorites' name='Favorites1'>1</a> 
<a href='#' class='Favorites' name='Favorites2'>2</a> 
<a href='#' class='Favorites' name='Favorites..'>..</a> 
<a href='#' class='Favorites' name='Favorites1000'>1000</a> 

然後用

$('.Favorites').on('click', function() { 
    alert(this.name); 
}); 

我敢肯定,你應該只有每一個DOM「id」屬性具有典型的具體價值。 http://www.w3schools.com/tags/att_global_id.asp w3schools id attribute documentation

相關問題