2015-04-04 67 views
0

我有以下HTML:jQuery的 - addClass不工作

<div class="b-250"> 
    <div id="c6281_701_1" class="sam-container sam-place" data-sam="1"> 
    <a id="a55_701" class="sam_ad" target="_blank" href="XYZ"> 
     <img alt="" src="XYZ"> 
    </a> 
    </div> 
</div> 

<script> 
    jQuery(document).ready(function(){ 
     console.log('try it - window ready'); 
     //jQuery('div.sam_ad').find('img').addClass('wp-post-image article- thumbnail'); 
     console.log(jQuery(".b-250").find('div')); 
     jQuery(".b-250").find('div').addClass("home-post has-post-thumbnail post"); 
     console.log('did it - window ready'); 
    }); 
</script> 

我不能设法几类添加到元素与sam_ad类。我试过jQuery('.sam_ad')...或以上的不同方法。

任何线索?

感谢

回答

2

使用:

jQuery(".sam_ad").addClass("home-post has-post-thumbnail post");

相反的:

jQuery(".b-250").find('div').addClass("home-post has-post-thumbnail post");

应该只是罚款。

在这种example filddle,它添加了类:

<a id="a55_701" class="sam_ad home-post has-post-thumbnail post" target="_blank" href="XYZ"> 

确保你已经包括jQuery库


如果您正在使用WordPress的(因为它似乎你),你可能需要在文档就绪功能中包装你jQuery:

jQuery(document).ready(function() {   
    console.log('try it - window ready'); 
    jQuery(".sam_ad").addClass("home-post has-post-thumbnail post"); 
    console.log('did it - window ready'); 
}); 
0

感谢您的在正常情况下,答案是正确的。

我发现有一些奇怪的ajax-request工作会呈现.sam_ad-Object。所以默认的document.ready-function不适用于这些对象,因为它们在dom准备好的时候没有被渲染。

,所以我切换到window.load,工作正常..

0

只需更新的jQuery版本为1.12或更高版本

function modify_js_cdn() { 
    if (! is_admin()) { 
     // comment out the next two lines to load the local copy of jQuery 
     wp_deregister_script('jquery'); 
     wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', false, '1.12.4'); 
     wp_enqueue_script('jquery'); 
    } 
} 

add_action('init', 'modify_js_cdn');