jQuery中Ajax快捷方法之$.getScript()
本节演示 提问
$.getScript()使用一个HTTP GET请求从服务器加载并执行一个 JavaScript 文件,书写格式如下
jQuery.getScript( url [, success(script) ] )
url 类型: String 一个包含发送请求的URL字符串
success(script)类型: Function()当请求成功后执行的回调函数
本节课程实例代码
(function() {
var url = "https://raw.github.com/jquery/jquery-color/master/jquery.color.js";
$.getScript(url, function() {
$("#go").click(function(){
$(".block")
.animate( { backgroundColor: "rgb(255, 180, 180)" }, 1000 )
.delay(500)
.animate( { backgroundColor: "olive" }, 1000 )
.delay(500)
.animate( { backgroundColor: "##1ab" }, 1000 );
});
});
})();
我们知道在jQuery中animate()方法并不能执行让北京颜色进行变化的函数,因为颜色值不像宽度高度等值是固定可变的,因此我们只能依赖color插件实现上述功能,所以我们先使用$.getScript()方法将color插件加载下来之后,再去执行颜色动画
<!-- HTML代码片段中请勿添加<body>标签 //-->
<button id="go">»点击加载js插件</button>
<div class="block"></div>
<!-- 推荐开源CDN来选取需引用的外部JS //-->
<script type="text/javascript" src="http://cdn.gbtags.com/jquery/1.11.1/jquery.min.js"></script>
/*CSS源代码*/
button{
display:inline-block;
padding:6px 10px;
border:1px solid transparent;
border-radius:4px;
background:#1aba85;
color:#fff;
font-size:13px;
text-align:center;
line-height:1.4;
margin:5px;
cursor:pointer;
}
div{
width:120px;
height:100px;
background:#1ab;
margin:5px;
border-radius:4px;
}
/*Javascript代码片段*/
(function() {
var url = "https://raw.github.com/jquery/jquery-color/master/jquery.color.js";
$.getScript(url, function() {
$("#go").click(function(){
$(".block")
.animate( { backgroundColor: "rgb(255, 180, 180)" }, 1000 )
.delay(500)
.animate( { backgroundColor: "olive" }, 1000 )
.delay(500)
.animate( { backgroundColor: "##1ab" }, 1000 );
});
});
})();