2015-04-04 69 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');