Javascript jQuery id 选择器仅适用于第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11114622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:31:45  来源:igfitidea点击:

jQuery id selector works only for the first element

javascriptjqueryhtml

提问by Mafaik

I have 3 buttons with same id, I need to get each button value when he's being clicked.

我有 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>

Here is my current jQueryscript:

这是我当前的jQuery脚本:

$("#xyz").click(function(){
      var xyz = $(this).val();
      alert(xyz);
});

But it works only for the first button, clicking on the other buttons are being ignored.

但它只适用于第一个按钮,点击其他按钮被忽略。

回答by gdoron is supporting Monica

I have 3 buttons with same id ...

我有 3 个具有相同 ID 的按钮...

You have invalid HTML, you can't have more than one element in a page with the 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.

7.5.2元素标识符:id 和 class 属性

id = name [CS]
此属性为元素分配名称。此名称在文档中必须是唯一的。

Solution: change from idto class,

解决方案:从 更改idclass

<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>

And the jQuery code:

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 #idselector docs:

jQuery#id选择器文档

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.

每个 id 值在一个文档中只能使用一次。如果多个元素被分配了相同的 ID,则使用该 ID 的查询将只选择 DOM 中第一个匹配的元素。但是,不应依赖这种行为;具有多个元素使用相同 ID 的文档是无效的。

If you look at the jQuery source you can see when you call $with an id selecor-($("#id")), jQuery calls the native javascript document.getElementByIdfunction:

如果您查看 jQuery 源代码,您会发现当您$使用 id selecor-( $("#id")) 进行调用时,jQuery 会调用本机 javascriptdocument.getElementById函数:

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

Though, in the specof document.getElementByIdthey didn't mention it must return the first value, this is how most of (maybe all?) the browsers implemented it.

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

DEMO

演示

回答by campino2k

ID means "Identifier" and is valid only once per document. Since your HTML is wrong at this point, some browsers pick the first, some the last occuring element with that ID.

ID 的意思是“标识符”,每个文件只能使用一次。由于此时您的 HTML 是错误的,因此某些浏览器会选择第一个出现的具有该 ID 的元素,有些则选择最后出现的元素。

Change ids for names would be a good step.

更改名称的 id 将是一个很好的步骤。

Then use $('button[name="xyz"]').click(function(){

然后使用 $('button[name="xyz"]').click(function(){

回答by Michel Hua

From my experience, if you use $('button#xyz')selector instead it will work. That's a hack, but it's still invalid HTML.

根据我的经验,如果您使用$('button#xyz')选择器,它将起作用。这是一个 hack,但它仍然是无效的 HTML。

回答by jagad89

this also worked if you have multiple element with same id.

如果您有多个具有相同 ID 的元素,这也有效。

 $("button#xyz").click(function(){
  var xyz = $(this).val();
  alert(xyz);
 });

you can check HERE

你可以在这里查看

回答by Liam

If you have same id in a container you can use on() to access each element for every event

如果容器中有相同的 id,则可以使用 on() 访问每个事件的每个元素

$("#containers").on("click","#xyz",function(){
  alert($(this).val())
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="containers">

<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>

</div>

and info about on() is here

关于 on() 的信息在这里

回答by Andrew

Although changing the id's to a class is better, you can get all the elements with the same id using the attribute equals selector:

尽管将 id 更改为类更好,但您可以使用属性 equals 选择器获取具有相同 id 的所有元素:

$('[id="xyz"]')

Or this to get only buttons with id xyz:

或者这样只获取带有 id xyz 的按钮:

$('button[id="xyz"]')

Or divs with id xyz:

或者 id 为 xyz 的 div:

$('div[id="xyz"]')

etc.

等等。

Alternatively you could use the "Attribute Contains Selector"to get all elements with ids that contain "xyz":

或者,您可以使用“属性包含选择器”来获取 ID 包含“xyz”的所有元素:

$('[id*="xyz"]')

Of course, this means all elements with id that partially contain "xyz" will get selected by this.

当然,这意味着所有 id 部分包含“xyz”的元素都将被选中。

回答by aymen

You can't have the same id because id is unique in page HTML. Change it to class or other attribute name.

您不能拥有相同的 id,因为 id 在页面 HTML 中是唯一的。将其更改为类或其他属性名称。

$('attributename').click(function(){ alert($(this).attr(attributename))});