2016-05-13 76 views
0

我想在頁面加載加載CSS背景圖像,但我收到此錯誤遺漏的類型錯誤:無法設置的不確定

Uncaught TypeError: Cannot set property 'background' of undefined

function loadBG() { 
    document.getElementsByClassName("img-icon-invite").style.background = "url('<?php echo Yii::app()->theme->baseUrl; ?>/style/home/images/firstProPopup-sprite-new-white.png')"; 
    document.getElementsByClassName("img-icon-verified").style.background = "url('http://dev1.venturepact.com/themes/adminre/style/home/images/firstProPopup-sprite-new-white.png')"; 
} 

window.onload = loadBG(); 
+0

份額HTML以及 – guradio

+1

'getElementsByClassName'獲取值的數組,你在它的名字'getElements' –

+0

看到'getElementsByClassName'返回一個數組,所以你需要訪問的每個元素由其索引。 –

回答

3

由於元素getElementsByClassName返回數組,你需要財產「背景」指定指數也

​​

或者使用jQuery你可以做,

$(".img-icon-invite").css('background-image', 'url(' + imageUrl + ')'); 
0

至於你提到的jQuery:

function loadBG(){ 
     $(".img-icon-invite").css('background-image', "url('<?php echo Yii::app()->theme->baseUrl;?>/style/home/images/firstProPopup-sprite-new-white.png')"; 
     $(".img-icon-verified").css('background-image',"url('http://dev1.venturepact.com/themes/adminre/style/home/images/firstProPopup-sprite-new-white.png')"; 

} 
$(document).ready(loadBG); 
相關問題