if contains certain text, then run jquery

﹥>﹥吖頭↗ 提交于 2019-11-30 16:40:03

问题


I need to run a jquery only if the bold element contains particular text. What am I doing wrong?

 <script>
 if ($('b:contains('Choose a sub category:')')) {

 $("td.colors_backgroundneutral").css("background-color","transparent");
 $("td.colors_backgroundneutral").children(':first-child').attr("cellpadding","0");
 };
 </script>

回答1:


Besides using single quotes inside single quotes, which breaks the string, you're using a jQuery selector inside an if statement. This selector only filters your b tags to those which contain "Choose a sub category"; and then returns a list of those elements. It does not return a boolean. Instead, use the .contains() method, like so:

if($("b").contains("Choose a sub category")) {
   // do stuff 
}

You can read more here

EDIT: since the .contains() method appears to be deprecated, here's a pure JS solution:

var el = document.getElementById("yourTagId") // or something like document.getElementsByTagName("b")[0] if you don't want to add an ID.
if (el.innerHTML.indexOf("Choose a sub category") !== -1) {
    // do stuff
}



回答2:


I have always used this to determine if an element exists:

if ($('b:contains("Choose a sub category:")').length > 0) { /*do things*/}



回答3:


 if ($("b").has(":contains('Choose a sub category:')").length) { 
 /*Your Stuff Here*/
 }


来源:https://stackoverflow.com/questions/6309870/if-contains-certain-text-then-run-jquery

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