jQuery if element在类字符串中是否有类

时间:2013-12-16 22:53:12

标签: jquery this addclass

我已在div内以#content的身份在我的网页上动态创建了文章。这些文章有很多类,例如

<article id="post-126" class="post-126 post type-post status-publish format-standard hentry category-all-portfolio category-detached portfolio_post target">

<article id="post-125" class="post-125 post type-post status-publish format-standard hentry category-all-portfolio category-terraced portfolio_post">

我想在这些文章中添加一个额外的类,只要它包含某个类。例如,如果文章包含“category-detached”类(第一个类),我想向它添加一个类“target”。

这是我尝试过的,但它不起作用

$(document).ready(function(){

if($('#content article').hasClass('category-detached')){
    $(this).addClass('target'); 
}
});

2 个答案:

答案 0 :(得分:3)

在您的情况下,

this是窗口而不是元素。

只是做:

var $elem = $('#content article');
if($elem.hasClass('category-detached')){
    $elem.addClass('target'); 
}

   $('#content article').addClass(function(){
        if($(this).hasClass('category-detached')) return "target";
   });

答案 1 :(得分:2)

最简单的解决方案。

$('#content article.category-detached').addClass('target'); 

它不起作用的原因是因为this未被引用到元素的上下文中。

如果您将其切换为以下内容,则会修改this以引用您收藏的每个元素。

$('#content article').each(function() {
    if($(this).hasClass('category-detached')){
        $(this).addClass('target'); 
    }
});