<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中,他们没有提到它必须返回第一个值,这是大多数(可能都是?)浏览器实现它的方式.