0

如果 LI 中有某些文本,我需要检查 jQuery 并相应地添加一个类。

沿着这些路线的东西......

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' : '';
});
4

1 回答 1

5

您正在做的是使用长度检查元素是否存在,如果不存在,则向该元素添加一个类?这不起作用,因为元素不存在,并且在 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' : '';
});
于 2013-05-22T16:01:47.530 回答