【问题标题】:I need to find if a class exists in a div tag (catch is I only know part of the classname)我需要查找一个类是否存在于 div 标签中(注意我只知道类名的一部分)
【发布时间】:2012-07-26 15:55:34
【问题描述】:

我在一个 div 容器中有 3 个 div,我遍历它们中的每一个。我需要检查类名是否匹配某个值。问题是我只知道类名的一部分。

例如:我只是以星球大战为例来说明我的情况。 我只知道我的类名应该是 R2XX 我如何从下面提到的 3 中检索 R2D2 和 R2D5

<div class="DIV_HORZ"> --container div
    <div class="R2D5"></div>
    <div class="C3P0"></div>
    <div class="R2D2"></div>
</div>

javascript部分:

$(".DIV_HORZ > div[id]").each(function(){
 ***find div whose class matches R2 + something***
});

【问题讨论】:

标签: jquery html jsp-tags


【解决方案1】:

您可以使用attribute-starts-with selector:

$('.DIV_HORZ > div[class^="R2"]')

【讨论】:

    【解决方案2】:

    除了开头选择器之外,您还可以使用 .each() 循环并使用您自己的自定义代码,包括正则表达式:

    $(".DIV_HORZ > div[id]").each(function(){
        if (this.id.match(/^R2/) {
            // found a matching id, process the item here
        }
    });
    

    正则表达式或代码显然可以随心所欲。如果需要,它可以使用仅内置选择器引擎所具有的更多逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2021-04-10
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多