【问题标题】:jquery getElementsByClassName find partial class name [duplicate]jquery getElementsByClassName 查找部分类名[重复]
【发布时间】:2014-06-13 20:10:34
【问题描述】:

我想使用 javascript 函数 getElementsByClassName 来循环一些没有确切类名的 html div,但它以相同的文本开头:“akordeon-item”

因此,html 文本如下所示:

<div class="akordeon-item akordeon-item-first">

<div>
    <span class="userid">
          blabla@yahoo.com
    </span>
</div>
</div>
<div class="akordeon-item akordeon-item-second">

<div>
    <span class="userid">
          john_doe@yahoo.com
    </span>
</div>
</div>
<div class="akordeon-item akordeon-item-third">

<div>
    <span class="userid">
          john_doe2@yahoo.com
    </span>
 </div>
 </div>

 <div class="akordeon-item akordeon-item-fourth">

<div>
    <span class="userid">
          john_doe3@yahoo.com
    </span>
</div>

另外,我尝试的javascript代码是这个:

var slides = getElementsByClassName(".akordeon-item");
for(var i = 0; i < slides.length; i++)
{
   alert("element : "+slides[i]);
}

我还尝试在 getElementsByClassName 方法中搜索此字符串:“akordeon-item”

我怎样才能使这个循环工作? 请帮忙...

【问题讨论】:

  • 问题似乎不清楚..!
  • 去掉句点.getElementsByClassName采用文字类名,不是选择器
  • 因为你标记了 jquery: $('[class^="text"]')
  • 请注意,除非搜索表达式有锚点,否则这样做会检查文档中的 所有 元素。

标签: javascript jquery html


【解决方案1】:

a bunch of special selectors你可以使用:

^= is starts with

$= is ends with    
=  is exactly equal
!= is not equal
*= is contains

试试:

$.each($('[class^="akordeon-item"]'), function(key, value) {
    console.log(key, value);
});

迭代集合的替代方法:

$('[class^="akordeon-item"]').each(function(key, value) {
    console.log(key, value);
});

或者使用for循环:

var slides = $('[class^="akordeon-item"]');
for (var i = 0; i < slides.length; i++) {
    console.log(slides[i]);
}

【讨论】:

  • 这将是function(index, value) { 更相关.. 因为它不会得到任何关键值..
  • @SomnathKharat 标题中的第一个单词是jquery。此外,该问题在jquery 下标记。
  • 他在标签中添加了 jquery
  • 以及如果使用这种 jQuery 方式 @somnathkharat 会有什么危害。
  • 非常感谢您的所有回答,这个最适合我。非常感谢@martynas!
【解决方案2】:
$('div[class^="akordeon-item"]').each(function(index){});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多