微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – jQuery id选择器仅适用于第一个元素

我有3个具有相同ID的按钮,我需要在单击时获取每个按钮值.

<button id="xyz" type="button" class="btn btn-primary" value="1">XYZ1</button>
<button id="xyz" type="button" class="btn btn-primary" value="2">XYZ2</button>
<button id="xyz" type="button" class="btn btn-primary" value="3">XYZ3</button>

这是我目前的jQuery脚本:

$("#xyz").click(function(){
      var xyz = $(this).val();
      alert(xyz);
});

但它只适用于第一个按钮,点击其他按钮被忽略.

解决方法:

I have 3 buttons with same id …

您的HTML无效,您在页面中不能有多个具有相同ID的元素.

Quoting the spec

7.5.2 Element identifiers: the id and class attributes

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

解决方案:从id更改为class,

<button type="button" class="btn btn-primary xyz" value="1">XYZ1</button>
<button type="button" class="btn btn-primary xyz" value="2">XYZ2</button>
<button type="button" class="btn btn-primary xyz" value="3">XYZ3</button>

和jQuery代码

$(".xyz").click(function(){
    alert(this.value);
    // No need for jQuery :$(this).val() to get the value of the input.
});

But it works only for the first button

jQuery #id选择器docs

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

如果你看一下jQuery源代码,当你用id selecor调用$时($(“#id”)),jQuery调用本机javascript document.getElementById函数

// HANDLE: $("#id")
} else {
    elem = document.getElementById( match[2] );
}

虽然,在document.getElementById的spec中,他们没有提到它必须返回第一个值,这是大多数(可能都是?)浏览器实现它的方式.

DEMO

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐