2017-09-20 131 views
0

我找不到這個代碼的問題,今晚我一直有太多的麻煩,任何人都可以幫我解決嗎?Javascript變量爲img src?

<html> 
    <script type="text/javascript"> 
     var image = new Array(); 
     image[0] = "header1.png"; 
     image[1] = "header2.png"; 
     image[2] = "header3.png"; 
     image[3] = "header4.png"; 
     var size = image.length 
     var x = Math.floor(size*Math.random()) 
     var backgroundImageFile = image[x]; 
     var backgroundImageUrl = "url('" + backgroundImageFile + "')"; 
     $('#header-image').css('background-image', 'backgroundImageUrl'); 
     function op() 
    { 
    document.getElementById('header-image').innerHTML=backgroundImageUrl; 
    } 
    </script> 
    <body onload="op();"> 
    <img src="backgroundImageFile"> 
    </body> 
    </html> 
+1

使用變量,而不是直接在報價包裝他們 - '$( '#頭圖像')的CSS( '背景圖片',backgroundImageUrl);' – gurvinder372

+0

什麼問題?什麼不起作用?你有什麼問題?你會得到什麼錯誤?你期望什麼行爲? –

+0

問題是什麼都沒有打印出來,而且我嘗試過和沒有引號,都沒有辦法。 – user8639974

回答

2

你可以試試這個:

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    var image = new Array(); 
     image[0] = "https://www.w3schools.com/angular/pic_angular.jpg"; 
     image[1] = "https://www.w3schools.com/images/colorpicker.gif"; 
     image[2] = "https://www.w3schools.com/angular/pic_angular.jpg"; 
     image[3] = "https://www.gstatic.com/images/branding/googlelogo/2x/googlelogo_dark_color_84x28dp.png"; 
     var size = image.length 
     var x = Math.floor(size*Math.random()); 
     var backgroundImageFile = image[x]; 
$('#imageId')[0].setAttribute('src',backgroundImageFile); 
}); 

</script> 
</head> 
<body> 
//displays circle with dimensions 

    image here: 
    <img src="backgroundImageFile" id="imageId"> 

</body> 
</html> 
0

請找到解決辦法:我想你正在尋找相同。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<html> 
 
    <script type="text/javascript"> 
 
     var image = new Array(); 
 
     image[0] = "header1.png"; 
 
     image[1] = "header2.png"; 
 
     image[2] = "header3.png"; 
 
     image[3] = "header4.png"; 
 
     var size = image.length 
 
     var x = Math.floor(size*Math.random()) 
 
     var backgroundImageFile = image[x]; 
 
     var backgroundImageUrl = "url('" + backgroundImageFile + "')"; 
 
     $('#header-image').css('background-image', 'backgroundImageUrl'); 
 
     function op() 
 
    { 
 
    document.getElementById('header-image').innerHTML=backgroundImageUrl; 
 
    } 
 
    </script> 
 
    <body onload="op();"> 
 
    <img src="backgroundImageFile"> 
 
    <div id="header-image"></div> 
 
    </body> 
 
    </html>