【发布时间】: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