jQuery 隐藏所有具有相同 id 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15475094/
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-26 15:07:53  来源:igfitidea点击:

jQuery hide all elements with the same id

jquery

提问by GiacomoLicari

by topic I have some divs with id = "loader".

按主题,我有一些 id = "loader" 的 div。

In my jQuery code I have

在我的 jQuery 代码中,我有

  $("#loader").hide(),

but it works only with the first div.

但它只适用于第一个 div。

How could I hide all the divs?

我怎么能隐藏所有的div?

Thanks a lot.

非常感谢。

回答by Kasyx

Having more than one element with the same ID is not valid HTML. You can only have one element with the ID (#loader) in the whole page. That's why jQuery is hiding only the first element. Use the class instead of the id:

具有相同 ID 的多个元素不是有效的 HTML。#loader整个页面中只能有一个带有 ID ( ) 的元素。这就是 jQuery 只隐藏第一个元素的原因。使用类而不是 id:

$('.loader').hide();

回答by Adil

The ids of html elements should be uniqueso you better use class with all element and use class selectorto hide them all.

html 元素的 id 应该是唯一的,因此您最好将 class 与所有元素一起使用,并使用class 选择器将它们全部隐藏。

$('.className').hide();

If it is not possible for you to assign common class to them for instance you can notchange the source code you can use Attribute Equals Selector [name=”value”].

如果您无法为它们分配公共类,例如您can not更改源代码,则可以使用Attribute Equals Selector [name=”value”]

 $("[id=loader]").hide();

回答by GregoryErasmus

A way to hide all items of the same ID was as follows

隐藏相同ID的所有项目的方法如下

$( "#hide" ).click(function() {
  $('div#hidden').hide();
});
<div id="hidden">ID Number 1</div>
<div id="2">ID Number 2</div>
<div id="hidden">ID Number 1</div>
<div id="2">ID Number 2</div>
<div id="hidden">ID Number 1</div>
<a href="#" id="hide">Hide Div</a>

Hope you can find this helpful.

希望你能发现这有帮助。