我有 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 会调用 native javascript document.getElementById
函数:
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
}
虽然,在 spec document.getElementById
他们没有提到它必须返回第一个值,这是大多数(也许是全部?)浏览器实现它的方式。
关于javascript - jQuery ID 选择器仅适用于第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114622/