jQuery:检查div是否包含文本,然后执行操作 [英] Jquery: Checking to see if div contains text, then action

查看:111
本文介绍了jQuery:检查div是否包含文本,然后执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在jQuery中检查div是否包含一些文本,然后添加一个类(如果有).

I'm trying to check in jQuery if a div contains some text, and then add a class if it does.

所以我写了这样的东西:

So I wrote something like this:

    if( $("#field > div.field-item").text().indexOf('someText') = 0) {
        $("#somediv").addClass("thisClass");
    }

我没有让它起作用.

<div id="field"><div class="field-item">someText</div></div>

<div id="somediv"></div>

这不正确吗?

推荐答案

您的代码包含两个问题:

Your code contains two problems:

  • JavaScript中的相等运算符为==,而不是=.
  • jQuery.text()将匹配元素的所有文本节点连接到单个字符串中.如果您有两个连续的元素,其中第一个包含'some',第二个包含'Text',那么您的代码将错误地认为存在一个包含'someText'的元素.
  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

我建议改为:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

这篇关于jQuery:检查div是否包含文本,然后执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆