检查某些文本并添加类

Check for certain text and add class

本文关键字:添加 文本 检查      更新时间:2023-09-26

我需要用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");
}

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

编辑:这是准确的代码,感谢adeneo的回答下面为我工作…

$('.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' : '';
});

你正在做的是检查一个元素是否存在通过使用长度,如果它不存在,添加一个类到该元素?这将不起作用,因为元素不存在,并且在像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' : '';
});