具有相同id的多个元素获取名称

时间:2015-09-16 13:50:36

标签: javascript jquery

我有多个元素

<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);
}); 

但它仅适用于第一个元素,其他元素不会对点击事件做出反应

如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

id应该是唯一的,因此您需要使用class,否则它只会选择id

的第一个dom元素

$(".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 :(得分:1)

我认为问题是jquery选择器#Favourites只是为了找到一个“id”#id;具有该值,因此忽略其他值。

你可以考虑转换收藏夹&#39;成为一个类:

<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的属性通常具有特定值。 http://www.w3schools.com/tags/att_global_id.asp w3schools id attribute documentation

相关问题