Jquery “contains” multiple values

拟墨画扇 提交于 2019-12-07 04:48:50

问题


I am finding all the divs in a document which contains inside a text: 'thetext' and i am changing this text:

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

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

 })

Is it possible to put inside contains multiple values? I would like to find the divs whic contains: 'thetext', but also another values, for example: 'thetext1', 'thetext2',etc

I`d want to make it in one procedure and not in more: dont want to use as many procedures as texts i´d like to find.

Thanks!


回答1:


You can use the multiple selector as a or condition like

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



回答2:


A selector like this provides an OR condition -

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

A selector like this provides an AND condition -

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

Demo - http://jsfiddle.net/jayblanchard/3a72h/




回答3:


You can have an array

var array = ['John', 'Martin'];


$(array).each(function () {

    $("div:contains(" + this + ")").css("text-decoration", "underline");

});

WORKING EXAMPLE




回答4:


Just adding one more point to above answers, if you want to select elements that dont have particular values then you can use

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

works as and condition




回答5:


You can create an array and loop it:

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");
    });
}


来源:https://stackoverflow.com/questions/23248809/jquery-contains-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!