我有3个具有相同ID的按钮…
引用规格:
7.5.2
:从更改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>
和 :
$(".xyz").click(function(){
alert(this.value);
// No need for jQuery :$(this).val() to get the value of the input.
});
但这仅适用于第一个按钮
jQuery #id
选择器文档:
每个id值在文档中只能使用一次。 但是,不应依赖此行为。包含多个使用相同ID的元素的文档无效。
如果您查看jQuery源,则可以看到$
使用id selecor-($("#id")
)进行调用时,jQuery会调用本机javascriptdocument.getElementById
函数:
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
}
尽管在他们的规范中document.getElementById
没有提到它必须返回第一个值,但这是大多数(也许是全部?)浏览器实现它的方式。