如果包含某些文本,则运行jquery [英] if contains certain text, then run jquery
问题描述
只有在粗体元素包含特定文本时才需要运行jquery。我做错了什么?
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>
推荐答案
除了在单引号内使用单引号外,还打破了你在if语句中使用jQuery选择器。 此选择器仅过滤 b
标记包含选择子类别的那些;然后返回这些元素的列表。它不返回布尔值。 而是使用 .contains()
方法,如下所示:
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
编辑,因为 .contains()
方法似乎不推荐使用,这是一个纯粹的JS解决方案:
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
}
这篇关于如果包含某些文本,则运行jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!