简体   繁体   English

jQuery span:包含不起作用

[英]Jquery span:contains doesn't work

i need to enable a div only if a span has certain text, yet the div gets enabled no matter what i put in the "contains" brackets. 我仅在跨度具有某些文本的情况下才需要启用div,但是无论我在“包含”括号中输入什么内容,div都将启用。 Even random gibberish. 甚至是乱七八糟的东西。 In my page's head I reference google's jquery 在页面的头部,我引用了Google的jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

Then run my script right before the closing body tag 然后在结束body标签之前运行我的脚本

<script>
if($("span:contains('abc123')")){
document.getElementById("mydiv").style.display = "block";
}
</script>

What am I doing wrong? 我究竟做错了什么? Thanks a lot for any help!! 非常感谢您的帮助!

I would do something like below: 我会做如下的事情:

<script>
if($("span:contains('abc123')").length > 0){
$("#mydiv").css("display","block")
}
</script>

You have to check if the element actually exists. 您必须检查该元素是否实际存在。 A selector will always return a truthy value. 选择器将始终返回真实值。 The length property will tell you how many of those elements there are in the collection, if any: length属性将告诉您集合中有多少个这些元素(如果有):

if( $("span:contains('abc123')").length ) { 
  //^^ elements exist
}

yes, I believe this is already answered, but just to add on: 是的,我相信这已经得到了回答,但请补充:

if( $("span:contains('abc123')").length ) { 
  $("#mydiv").show();
}

I think this works better, since you already have jQuery on the page. 我认为这样做效果更好,因为您已经在页面上安装了jQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM