jQuery 如何使用jQuery选择多个元素

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

How to select multiple elements with jQuery

jqueryhtmlajax

提问by RiceBucket

I'm new to JQuery/Javascript etc... based on the following article: How to make an anchor tag refer to nothing?

我是 JQuery/Javascript 等的新手……基于以下文章: 如何使锚标记不引用任何内容?

I would like to apply the java function to several id's. Can we not make the function execute for classes as opposed to ids?

我想将java函数应用于几个id。我们不能让函数为类而不是 id 执行吗?

<span class="style1" id="myid">Link</span> 
<span class="style1" id="myid">Link</span>
<span class="style1" id="myid">Link</span>
<span class="style1" id="myid">Link</span>
<span class="style1" id="myid">Link</span>

$('myid').click(function() { 
    /* put your code here */ 
}); 

Basically as above, how do I execute the function above for ALL of the links? Is this possible? Thanks in advance.

基本上如上所述,我如何为所有链接执行上述功能?这可能吗?提前致谢。

回答by Sujit Agarwal

you should name the IDs uniquely,

您应该唯一地命名 ID,

<span class="style1" id="myid1">Link</span> 
<span class="style1" id="myid2">Link</span>
<span class="style1" id="myid3">Link</span>
<span class="style1" id="myid4">Link</span>
<span class="style1" id="myid5">Link</span>

then use this code

然后使用此代码

$('#myid1,#myid2,#myid3,#myid4,#myid5').click(function() { 
    /* put your code here */ 
}); 

回答by Scorpion-Prince

Use the following

使用以下

$('.style1').click(function() {      
    /* put your code here */  
}); 

This adds a click handler to all elements with class containing style1. You should not have duplicate IDs

这会向所有类包含style1. 您不应该有重复的 ID

回答by Rocket Hazmat

First off, IDs should be unique. You should not have multiple elements with the same ID.

首先,ID 应该是唯一的。不应有多个具有相同 ID 的元素。

To select by ID in jQuery use the #character. $('#myid'). This will get the first element with that ID, as there should only be one (you can kinda cheat by doing $('[id="myid"]')to get get multiple elements with the same ID).

要在 jQuery 中按 ID 选择,请使用#字符。 $('#myid'). 这将获得具有该 ID 的第一个元素,因为应该只有一个(您可以通过$('[id="myid"]')获取多个具有相同 ID 的元素来作弊)。

I suggest using a class to select all of your links. Classes are selected using the .character.

我建议使用一个类来选择所有链接。使用.字符选择类。

$('.style1').click(function(){});