jQuery實現輪播圖時出現ready方法外無法調用方法(函數) 遇到的問題: 解決ready()方法外調用方法(函數)問題(修改紅色代碼即可): 方法一: 方法二: ...
jQuery實現輪播圖時出現ready方法外無法調用方法(函數)
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>Insert title here</title> 6 <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script> 7 <script type="text/javascript"> 8 var image = ["https://img1.360buyimg.com/pop/jfs/t1/15215/22/10893/142189/5c8b26eeEbf3f7b19/3d8f4b6e982e2ceb.jpg", 9 "https://img1.360buyimg.com/pop/jfs/t1/17925/40/8815/90463/5c78bd5dEfa47279e/8d85b9b3b10179df.jpg", 10 "https://m.360buyimg.com/babel/jfs/t1/20721/30/12006/93636/5c94e1d7E2543f373/bf731a518fed103e.jpg", 11 "https://img1.360buyimg.com/pop/jfs/t1/20083/28/11964/95576/5c937e34Ecfb4ea55/60029bdeab133ce1.jpg"]; 12 var i = 1; 13 var lunbo;//定義全局變數 14 $(document).ready(function(){ 15 $("div").css("background-image",'url('+image[0]+')'); 16 lunbo = function(){ 17 //將lunbo函數賦給lunbo變數 18 $("div").css("background-image","url("+image[i]+")"); 19 i++; 20 if(i > 3){ 21 i = 0; 22 } 23 } 24 }) 25 setInterval("lunbo()",2000); 26 </script> 27 </head> 28 <body> 29 <div style="width:590px; height:470px; margin:auto;"></div> 30 </body> 31 </html>
調試
備註
遇到的問題:
- div標簽未設置width和height屬性導致background-image屬性失效。
- ready()方法外調用lunbo()方法無效。
解決ready()方法外調用方法(函數)問題(修改紅色代碼即可):
方法一:
1 $(document).ready(function(){ 2 $("div").css("background-image",'url('+image[0]+')'); 3 }) 4 function lunbo(){ 5 //將lunbo函數放在ready()方法外供全局調用 6 $("div").css("background-image","url("+image[i]+")"); 7 i++; 8 if(i > 3){ 9 i = 0; 10 } 11 } 12 setInterval("lunbo()",2000);
方法二:
1 var lunbo;//定義全局變數 2 $(document).ready(function(){ 3 $("div").css("background-image",'url('+image[0]+')'); 4 lunbo = function(){ 5 //將lunbo函數賦給lunbo變數 6 $("div").css("background-image","url("+image[i]+")"); 7 i++; 8 if(i > 3){ 9 i = 0; 10 } 11 } 12 }) 13 setInterval("lunbo()",2000);