【问题标题】:Check for certain text and add class检查某些文本并添加类
【发布时间】:2013-05-22 15:58:17
【问题描述】:

我需要用 jQuery 检查 LI 中是否有某些文本并相应地添加一个类。

类似的东西...

if ($('ul li:last-child:contains("this text")').length > 0) {
    $(this).addClass("this");
} else if ($('ul li:last-child:contains("that text")').length > 0)
    $(this).addClass("that");
}

显然,上面的代码不起作用,但希望它接近我所需要的。有人知道我怎么写吗?

编辑: 感谢下面adeno的回答,这是对我有用的确切代码......

$('.job-result .job-details ul li:last-child').addClass(function() {
    return $(this).text().indexOf('Augusta') != -1 ? 'augusta' : 
           $(this).text().indexOf('Aiken') != -1 ? 'aiken' :
           $(this).text().indexOf('Job') != -1 ? 'jobshop' : '';
});

【问题讨论】:

  • $(this) 指的是什么?
  • $('ul li:last-child').html() == '你的文字'
  • 天啊。我很欣赏对这个问题的反对意见。对我来说似乎是合法的,并从 adeneo 那里得到了我正在寻找的答案。

标签: javascript jquery contains


【解决方案1】:

您正在做的是使用长度检查元素是否存在,如果不存在,则向该元素添加一个类?这不起作用,因为元素不存在,并且在 if / else 这样的条件内没有特殊范围,所以this 没有意义?

如何在addClass() 中使用匿名函数来获取范围并检查内容:

$('ul li:last-child').addClass(function() {
    return $(this).text().indexOf('this text') != -1 ? 'this' : 
           $(this).text().indexOf('that text') != -1 ? 'that' : '';
});

【讨论】:

  • 这完全符合我的需要。感谢您对逻辑的返工。我在我的问题中添加了我的确切用法,以帮助其他人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多