在 jQuery 中处理多个 ID

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

Handling multiple IDs in jQuery

jqueryjquery-selectors

提问by Rajeev

Can multiple ids be handled like in the code?

可以像在代码中那样处理多个 id 吗?

<script>
$("#segement1, #segement2, #segement3").hide()
</script>

<div id="segement1"/>
<div id="segement2"/>
<div id="segement3"/>

回答by Nick Craver

Yes, #idselectorscombined with a multiple selector(comma) is perfectly valid in both jQuery and CSS.

是的,#id选择器多重选择器(逗号)的组合在 jQuery 和 CSS 中都是完全有效的。

However, for your example, since <script>comes beforethe elements, you need a document.readyhandler, so it waits until the elements are in the DOM to go looking for them, like this:

但是,对于您的示例,由于<script>出现元素之前,您需要一个document.ready处理程序,因此它会等到元素在 DOM 中查找它们,如下所示:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

回答by Zeeshan Eqbal

Solution:

解决方案:

To your secondary question

你的次要问题

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

您可以使用该变量作为选择器的替换。

elem1.css({'display':'none'}); //will work

elem1.css({'display':'none'}); //将工作

In the below case selector is already stored in a variable.

在下面的情况下,选择器已经存储在一个变量中。

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

$(elem1,elem2,elem3).css({'display':'none'}); // 不管用