如果包含某些文本,则运行 jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6309870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:40:19  来源:igfitidea点击:

if contains certain text, then run jquery

jquerytextif-statementcontains

提问by user764728

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

仅当粗体元素包含特定文本时,我才需要运行 jquery。我究竟做错了什么?

 <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>

回答by Thomas Shields

Besides using single quotes inside single quotes, which breaks the string, you're using a jQuery selector inside an if statement. This selectoronly filters your btags 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 语句中使用了 jQuery 选择器。此选择器仅将您的b标签过滤为包含“选择子类别”的标签;然后返回这些元素的列表。它不返回布尔值。相反,使用该.contains()方法,如下所示:

if($("b").contains("Choose a sub category")) {
   // do stuff 
}
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:

编辑:由于该.contains()方法似乎已被弃用,这是一个纯 JS 解决方案:

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
}

回答by dev4life

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

我一直用它来确定一个元素是否存在:

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

回答by BTC

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