您的位置:首页 > Web前端 > JQuery

jQuery入门[4]-链式代码

2009-04-16 16:11 260 查看
jQuery另一个很令人惬意的地方是,一般的代码都是一行一行写,jQuery的代码可以一串一串写。
这一点,在前面的文章中已经介绍过了。
直接来一个Demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>chainning code</title>
<script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
//添加四个按钮
$('<input type="button" value="click me"/><input type="button" value="triggle click me"/><input type="button" value="detach handler"/><input type="button" value="show/hide text"/>').appendTo($('body'));
//找出所有按钮
$('input[type="button"]')
.eq(0)//找到第一个按钮
.click(function(){
alert('you clicked me!');
})
.end().eq(1)//返回所有按钮,再找到第二个
.click(function(){
$('input[type="button"]:eq(0)').trigger('click');
})
.end().eq(2)//返回所有按钮,再找到第三个
.click(function(){
$('input[type="button"]:eq(0)').unbind('click');
})
.end().eq(3)//返回所有按钮,再找到第四个
.toggle(function(){
$('.panel').hide('slow');
},function(){
$('.panel').show('slow');
});
});
</script>
<style type="text/css">
.panel
{
padding: 20px;
background-color: #000066;
color: #FFFFFF;
font-weight: bold;
width: 200px;
height: 50px;
}
</style>
</head>
<body>
<div class="panel">welcome to jQuery!</div>
</body>
</html>



现在,链式代码已经成为jQuery非常流行的一个特点了,在使用链条方式写代码时,可能会用到eq()/filter()……(reference:http://docs.jquery.com/Traversing)等方法变化jQuery对象的对应范围,然后,又可以用end()函数将范围复原到原来的状况。
需要注意的是,有几个函数并不返回jQuery对象,所以链条就不能继续下去,比如get()就不能像eq()那样用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: