我已在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');
}
});
答案 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');
}
});