jQuery 在jquery中查找具有特定属性值的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4958081/
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
Find all elements with a certain attribute value in jquery
提问by Pabuc
I need to find all elements that has a special attribute value.
我需要找到所有具有特殊属性值的元素。
Here is the div I need to find (I have many of them..)
这是我需要找到的 div(我有很多..)
<div imageId='imageN'>...
I simply need to loop through the divs which have imageId='imageN'
我只需要遍历具有 imageId='imageN'
回答by sammy34
Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:
虽然它没有准确地回答这个问题,但我在寻找一种方法来获取元素集合(可能是不同的标签名称)时,我来到这里,这些元素只有一个给定的属性名称(没有按属性值过滤)。我发现以下对我来说效果很好:
$("*[attr-name]")
Hope that helps somebody who happens to land on this page looking for the same thing that I was :).
希望能帮助那些碰巧在此页面上寻找与我相同的东西的人:)。
Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):
更新:似乎不需要星号,即基于一些基本测试,以下内容似乎与上述内容相同(感谢 Matt 指出这一点):
$("[attr-name]")
回答by ThiefMaster
$('div[imageId="imageN"]').each(function() {
// `this` is the div
});
To check for the sole existence of the attribute, no matter which value, you could use ths selector instead: $('div[imageId]')
要检查属性是否存在,无论是哪个值,都可以使用 ths 选择器: $('div[imageId]')
回答by Val
It's not called a tag; what you're looking for is called an html attribute.
它不称为标签;您要查找的内容称为 html 属性。
$('div[imageId="imageN"]').each(function(i,el){
$(el).html('changes');
//do what ever you wish to this object :)
});
回答by Krunal
You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:
您可以使用属性的部分值来使用 (^) 符号检测 DOM 元素。例如你有这样的 div:
<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...
You can use the code:
您可以使用以下代码:
var abc = $('div[id^=abc]')
This will return a DOM array of divs which have id starting with abc
:
这将返回一个 DOM div 数组,其 id 以abc
以下内容开头:
<div id="abc_1"></div>
<div id="abc_2"></div>
Here is the demo: http://jsfiddle.net/mCuWS/
这是演示:http: //jsfiddle.net/mCuWS/
回答by LostSenSS
Use string concatenation. Try this:
使用字符串连接。尝试这个:
$('div[imageId="'+imageN +'"]').each(function() {
$(this);
});