javascript – jQuery id选择器仅适用于第一个元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – jQuery id选择器仅适用于第一个元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1733字,纯文字阅读大概需要3分钟。
内容图文
![javascript – jQuery id选择器仅适用于第一个元素](/upload/InfoBanner/zyjiaocheng/717/48522e02c1cf4e93b339123899d7225d.jpg)
我有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的元素.
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中,他们没有提到它必须返回第一个值,这是大多数(可能都是?)浏览器实现它的方式.
内容总结
以上是互联网集市为您收集整理的javascript – jQuery id选择器仅适用于第一个元素全部内容,希望文章能够帮你解决javascript – jQuery id选择器仅适用于第一个元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。