jQuery实现轮播图
程序员文章站
2023-11-28 09:22:16
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);