javascript - jQuery ID 选择器仅适用于第一个元素

标签 javascript jquery html

我有 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 会调用 native javascript document.getElementById 函数:

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

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

DEMO

关于javascript - jQuery ID 选择器仅适用于第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114622/

相关文章:

javascript - 使用 jQuery 删除不同域中同名的 Cookie

javascript - 如何显示来自函数装饰器的消息?

javascript - 如何全局启用 ECMAScript "use strict"?

javascript - 在本地主机上保存文件

html - 将伪元素放置在 LI 内的嵌套列表之前

javascript - 单击带有表单的打开弹出窗口,然后提交下载并关闭它!如何?

javascript - 将 Google map 集中在数据库中的点上?

javascript - 如何使用另一个数组作为模板对数组数据进行排序?

javascript - 停止运行该脚本

jquery - 在页面加载时启动 jQuery Alert