【问题标题】:find elements which id contains two substrings查找 id 包含两个子字符串的元素
【发布时间】:2015-05-08 01:08:49
【问题描述】:

我有一个 HTML 表格,我需要使用 jquery 将 CSS 样式更改为所有 de <td>,其 "id" 包含子字符串 "_A_189" 和子字符串 "_B_V_852"。子字符串可以位于字符串的任何位置。

我用这个,但它不起作用:

$('id:contains("_A_189"):contains("_B_V_852")').css(style);

【问题讨论】:

    标签: javascript jquery substring contains


    【解决方案1】:

    您可以使用方括号按属性选择:

    $("[id*='_A_189'][id*='_B_V_852']").css(style);
    

    如果遇到这个问题,最好将其缩小到仅 td 元素:

    $("td[id*='_A_189'][id*='_B_V_852']").css(style);
    

    “[id*='str']”的意思是“在任何地方查找属性'id'包含字符串'str'的元素”。

    更多信息参见 jQuery 文档: http://api.jquery.com/attribute-contains-selector/

    编辑: 这个选择器在 css 中可用,不仅在 jQuery 中,所以如果 '_A_189' 和 '_B_V_852' 部分是静态的,你应该考虑将它添加到你的样式表而不是使用脚本。例如:

    table td[id*='_A_189'][id*='_B_V_852'] {
        /* your styles */
    }
    

    【讨论】:

    • 谢谢。这是最简单的方法。
    • 请注意,上面的代码将在 dom 上的每个 id 元素上运行 - op 只要求 td 元素,如果您指定只检查 td 元素的 id,它将运行得更快: $("td[id*='_A_189'][id*='_B_V_852']").css(style);
    • 是的,没错。此外,如果调用是为了编辑一个表的单元格,最好将其包含在 jQuery/css 选择器中: $("table#my_table_id td[id*='_A_189'][id*='_B_V_852' ]").css(样式);
    • 值得展示的是,您可以直接在 CSS 中选择这些元素(使用相同的选择器),而不是通过 jQuery。
    【解决方案2】:

    如果两个字符串可以是“in any position”,那么实际上选择它们的唯一方法是使用filter()

    // finds all <td> elements with an 'id', filters that collection:
    $('td[id]').filter(function () {
        // retains only those elements for which the assessment returns true
        // (the strings of both '_A_189' AND
        // the string '_B_V_852' must be found within the id property:
        return this.id.indexOf('_A_189') > -1 && this.id.indexOf('_B_V_852') > -1;
    // the found/retained elements remain in the chain, passed to
    // the css() method:
    }).css(/* style */);
    

    你最初的尝试:

    $('id:contains("_A_189"):contains("_B_V_852")').css(style);
    

    没有用,因为:contains() 选择器会查看元素的文本内容以查找您要搜索的字符串,而不是元素的属性/属性。

    另外,因为没有 .#: 或其他字符来指示,所以这个 jQuery 正在寻找 &lt;id&gt; 的元素类型,而不是查看 @987654335 的所有元素@ 属性,其文本包含提供给:contains() 选择器的字符串。

    参考资料:

    【讨论】:

      【解决方案3】:

      包含的正确 css 选择器是 [attribute*=substring],所以使用 jquery:

      $('[id*="_A_189"][id*="_B_V_852"]').css(style);

      【讨论】:

        【解决方案4】:

        你可以很简单地做到这一点:

        $( "td[id*='_A_189'][id*='_B_V_852']").css(style);
        

        【讨论】:

          猜你喜欢
          • 2016-03-03
          • 1970-01-01
          • 2015-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-19
          • 1970-01-01
          • 2016-04-19
          相关资源
          最近更新 更多