javascript jquery getElementsByClassName 查找部分类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24204832/
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
jquery getElementsByClassName find partial class name
提问by user3256429
I want to use the javascript function getElementsByClassName to loop in some html divs that don't have the exactly class name, but it starts with the same text: "akordeon-item"
我想使用 javascript 函数 getElementsByClassName 在一些没有确切类名的 html div 中循环,但它以相同的文本开头:“akordeon-item”
So, the html text looks like this:
因此,html 文本如下所示:
<div class="akordeon-item akordeon-item-first">
<div>
<span class="userid">
[email protected]
</span>
</div>
</div>
<div class="akordeon-item akordeon-item-second">
<div>
<span class="userid">
[email protected]
</span>
</div>
</div>
<div class="akordeon-item akordeon-item-third">
<div>
<span class="userid">
[email protected]
</span>
</div>
</div>
<div class="akordeon-item akordeon-item-fourth">
<div>
<span class="userid">
[email protected]
</span>
</div>
Also, the javascript code I tried is this one:
另外,我试过的 javascript 代码是这样的:
var slides = getElementsByClassName(".akordeon-item");
for(var i = 0; i < slides.length; i++)
{
alert("element : "+slides[i]);
}
I also tried searching for this string inside the getElementsByClassName method : "akordeon-item"
我还尝试在 getElementsByClassName 方法中搜索此字符串:“akordeon-item”
How can I make this loop work? Please help...
我怎样才能使这个循环工作?请帮忙...
回答by martynas
There is a bunch of special selectorsyou can make use of:
有一群特殊的选择器,你可以使用:
^= is starts with
$= is ends with
= is exactly equal
!= is not equal
*= is contains
Try:
尝试:
$.each($('[class^="akordeon-item"]'), function(key, value) {
console.log(key, value);
});
Alternative ways to iterate over the set:
迭代集合的替代方法:
$('[class^="akordeon-item"]').each(function(key, value) {
console.log(key, value);
});
Or using a for
loop:
或者使用for
循环:
var slides = $('[class^="akordeon-item"]');
for (var i = 0; i < slides.length; i++) {
console.log(slides[i]);
}
回答by RGS
$('div[class^="akordeon-item"]').each(function(index){});