简体   繁体   English

点击触发具有相同ID的多个元素的js函数

[英]Fire a js function on click for multiple elements with the same id

I have a number of links inside my ASP grid view. 我的ASP网格视图内有许多链接。 Each link is supposed to fire a Javascript function after clicking it by calling their respective ID. 每个链接都应该通过调用各自的ID来点击后触发Javascript函数。 Here is the code for it: 这是它的代码:

<script type="text/javascript">
  $(function () {
    $('#LkForgot').on('click', function (e) {
      alert("hi");
    });
  });
</script>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ReportId"CssClass="GridViewStyle">
<asp:TemplateField>
  <ItemTemplate>
    <asp:ImageButton CssClass="Link" ID="IMGDetail" ClientIDMode="Static" runat="server" ImageUrl="~/Img/Detail.png" />
  </ItemTemplate>
</asp:TemplateField>

All of them have the same ID, but only the first one successfully fires the function. 它们都具有相同的ID,但是只有第一个成功触发了该功能。 I want each link to separately fire the function. 我希望每个链接单独触发该功能。

<script type="text/javascript">
$(function () {
    $('.Link').on('click', function (e) {
        alert("hi");
    });
});

I don't now about asp but IDs are supposed to be unique. 我现在不讨论ASP,但ID应该是唯一的。 Try populating the IDs dynamically or try using classes. 尝试动态填充ID或尝试使用类。

You are using ID and it should unique , that's why it will work on only one element try with class. 您正在使用ID,并且ID应该是唯一的,这就是为什么它只能在尝试class的一个元素上使用的原因。 You can apply same class to multiple element. 您可以将同一类应用于多个元素。

<script type="text/javascript">
$(function () {
    $('.LkForgot').on('click', function (e) {
        alert("hi");
    });
});

You have to identify a unique attribute in the element and use that as the unique identifier. 您必须在元素中标识唯一属性,并将其用作唯一标识符。 It does not always have to be the 'id' tag. 它并不总是必须是'id'标签。 you could do something like this as well 你也可以做这样的事情

$("[ClientIDMode='Static']").bind("click", function(){console.log("clicked") })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM