【问题标题】:Jquery "contains" multiple valuesJquery“包含”多个值
【发布时间】:2014-06-08 13:15:34
【问题描述】:

我在包含文本的文档中找到所有 div:“thetext”,我正在更改此文本:

$("div:contains('thetext'):not(:has(*))").each(function () {

  $(this).text($(this).text() + " anotherTextAddedBefore");

 })

是否可以在里面放多个值? 我想找到包含:'thetext',还有其他值的 div,例如:'thetext1'、'thetext2'等

我想在一个过程中完成,而不是更多:不想使用与我想查找的文本一样多的过程。

谢谢!

【问题讨论】:

  • $("div:contains('thetext'), div:contains('thetext1'), div:contains('thetext2')") 是可能的
  • $("div:contains('thetext'):contains('thetext1'):contains('thetext2')")
  • 这不是与条件@A.Wolff 吗?
  • @JayBlanchard 是的,但这就是我理解问题的方式,我可能错了I would like to find the divs whic contains: 'thetext', but also another values, for example: 'thetext1', 'thetext2',etc
  • 啊,重读我明白你在说什么@A.Wolff

标签: javascript jquery contains


【解决方案1】:

您可以将多重选择器用作或条件

$("div:not(:has(*))").filter(":contains('thetext'), :contains('thetext2')").each(..)

【讨论】:

    【解决方案2】:

    这样的选择器提供了一个 OR 条件 -

    $("div:contains('thetext'), div:contains('thetext1'), div:contains('thetext2')")
    

    这样的选择器提供了一个 AND 条件 -

    $("div:contains('thetext'):contains('thetext1'):contains('thetext2')")
    

    演示 - http://jsfiddle.net/jayblanchard/3a72h/

    【讨论】:

      【解决方案3】:

      你可以有一个数组

      var array = ['John', 'Martin'];
      
      
      $(array).each(function () {
      
          $("div:contains(" + this + ")").css("text-decoration", "underline");
      
      });
      

      WORKING EXAMPLE

      【讨论】:

      • 谢谢下划线!它简短、简单且效果很好!
      【解决方案4】:

      在上面的答案中再多加一点,如果你想选择没有特定值的元素,那么你可以使用

      $("div:not(:contains('thetext'), :contains('thetext1'),:contains('thetext2'))")
      

      作为and 条件工作

      【讨论】:

        【解决方案5】:

        你可以创建一个数组并循环它:

        var containsVals = ["text1","text2"];
        
        for(var i=0;i<containsVals.length;i++){
            $("div:contains("+ containsVals[i] +"):not(:has(*))").each(function () {
              $(this).text($(this).text() + " anotherTextAddedBefore");
            });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-07
          • 1970-01-01
          • 1970-01-01
          • 2012-08-22
          • 2018-03-08
          • 2019-12-28
          相关资源
          最近更新 更多