使用getScript()方法异步加载并执行js文件

使用getScript()方法异步加载并执行js文件

使用getScript()方法异步请求并执行服务器中的JavaScript格式的文件,它的调用格式如下所示:

jQuery.getScript(url,[callback])$.getScript(url,[callback])

参数url为服务器请求地址,可选项callback参数为请求成功后执行的回调函数。

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3     <head>
 4         <title>使用getScript()方法异步加载并执行js文件</title>
 5         <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
 6         <style>
 7             #divtest
 8             {
 9                  282px;
10             }
11             #divtest .title
12             {
13                 padding: 8px;
14                 background-color:blue;
15                 color:#fff;
16                 height: 23px;
17                 line-height: 23px;
18                 font-size: 15px;
19                 font-weight: bold;
20             }
21             ul
22             {
23                 float: left;
24                  280px;
25                 padding: 5px 0px;
26                 margin: 0px;
27                 font-size: 14px;
28                 list-style-type: none;
29             }
30             ul li
31             {
32                 float: left;
33                  280px;
34                 height: 23px;
35                 line-height: 23px;
36                 padding: 3px 8px;
37             }
38             .fl
39             {
40                 float: left;
41             }
42             .fr
43             {
44                 float: right;
45             }
46         </style>
47     </head>
48     
49     <body>
50         <div id="divtest">
51             <div class="title">
52                 <span class="fl">我最喜欢的运动</span> 
53                 <span class="fr">
54                     <input id="btnShow" type="button" value="加载" />
55                 </span>
56             </div>
57             <ul></ul>
58         </div>
59         
60         <script type="text/javascript">
61             $(function () {
62                 $("#btnShow").bind("click", function () {
63                     var $this = $(this);
64                     $.getScript("./sport.js",function(){
65                         $this.attr("disabled", "true");
66                     });
67                 })
68             });
69         </script>
70     </body>
71 </html>
View Code
 1 var data = [{
 2         "name":"足球"
 3     },{
 4         "name":"篮球"
 5     },{
 6         "name":"乒乓球"
 7     },{
 8         "name":"排球"
 9 }];
10 $.each(data,function(index,sport){
11     $("ul").append("<li>"+sport['name']+"</li>");
12 });
View Code
原文地址:https://www.cnblogs.com/xuesen1995/p/4298051.html