我在我的drupal网站上使用jQuery。我不能通过使用jQuery将类添加到当前元素。
我把这个addclass放在带有alert的if条件中。警报工作正常。但是addclass不起作用。
if (jQuery(".explore_degree_widget_area li a").has(":contains('Associates')")) {
jQuery(this).addClass('icon_associate');
alert('Yes');
}
你能帮助我吗?
答案 0 :(得分:3)
如果条件始终为true,则 has()
会返回已过滤的jQuery对象。同样 has()
避免使用文本节点,只检查它的后代,您需要使用 filter()
。
jQuery(".explore_degree_widget_area li a").filter(":contains('Associates')").addClass('icon_associate');
或使用组合选择器
jQuery(".explore_degree_widget_area li a:contains('Associates')").addClass('icon_associate');
答案 1 :(得分:1)
this
是指上下文但不是元素。使用以下内容:
jQuery(".explore_degree_widget_area li a:contains('Associates')")
.addClass('icon_associate').each(function() {
alert('Yes'); // if you really want to have it
});
答案 2 :(得分:0)
尝试
$(".explore_degree_widget_area li a:has(:contains('Associates'))").addClass('icon_associate');