具有相同ID的多个a标签的jQuery单击事件 [英] JQuery click event for multiple a tags with same id

查看:130
本文介绍了具有相同ID的多个a标签的jQuery单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下div元素结构的HTML页面.

I have HTML page having below structure of div elements.

<div data-videos-list="listelement" id="band-comments-div">
<label>
    <!-- Some code here-->
    <br><a class="band-comments" href="review.html?bandName=Local Band">Click to review</a>
</label>

在此,div和一个标签重复多次.每个锚标记之间的唯一区别是每个href属性都不同. 我正在尝试处理每次出现的代码的click事件,如下所示.

Here, div and a tags are repeated multiple times. The only difference between each anchor tag is that href attribute is different for each. I am trying to handle the click event of every occurrence of the tag like below.

$("#band-comments-div a").on("click", function(event) {
event.preventDefault();

}});

但是由于div和标记多次出现,因此不会跟踪click事件.还有其他方法可以解决这个问题吗?

But since there are multiple occurrences of the div and a tags, the click event is not tracked. Is there any other way to handle this?

推荐答案

您不能为多个元素提供ID.您需要使用类.由于您要提供多个ID,因此它将仅跟踪首次出现的click事件.你可以做这样的事情.

You cannot give ID to multiple elements. You need to use class. Since you are giving multiple IDs it will only track the click event of first occurrence. You can do something like this.

<div data-videos-list="listelement" class="band-comments-div">
<label>
    <!-- Some code here-->
    <br><a class="band-comments" href="review.html?bandName=Local Band">Click to review</a>
</label>


$(docunment).on("click",".band-comments-div a", function(event) {
  event.preventDefault();
  alert($(this).attr("href"));
});

这样,您可以在点击事件中获取每个a标签的属性href.

This way you can get the attr href of each a tag on click event.

$(document).ready(function(){
 var href = ''; 
 $(docunment).on("click",".band-comments-div a", function(event) {
   event.preventDefault();
      href = $(this).attr("href");
  });
  alert(href);
});

这篇关于具有相同ID的多个a标签的jQuery单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆