jQuery之所以令人爱不释手,在于其强
大的选择器表达式令DOM操作优雅而艺术。
jQuery的选择符支持id,tagName,css1-3
expressions,XPath,参见:
href="http://docs.jquery.com/Selectors">http://docs.jquery.com/Selectors
DEMO:
re><!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>Selector</title>
<script src=”../scripts/jquery-
1.2.3.intellisense.js”
type=”text/javascript”></script>
</head>
<body>
<input
value=”1″ /> +
<input value=”2″ />
<input type=”button”
value=”=” />
<label> </label>
<script
type=”text/javascript”>
$(“input[type='button']“).click(function(){
var i = 0;
$(“input[type='text']“).each(function(){
i += parseInt($(this).val());
});
$(‘label’).text
(i);
});
$(‘input:lt(2)’)
.add(‘label’)
.css(‘border’,'none’)
.css(‘borderBottom’,'solid 1px navy’)
.css({‘width’:’30px’});
</script>
</body>
</html>
分解:
$("input[type='button']")用于找到type属性为button的input元素(此为CSS表达式,
IE7才开始支持,所以在 IE6中通常用jQuery的这种表达式代替CSS代码设置样式)。click()函数为
button添加click事件处理函数。
在button_click时,$("input[type='text']")找出所有输入框
,each()函数遍历找出来的数组中的对象的值,相加后设到label中。
$('input:lt(2)')
.add('label')
两行代码意为:所有input中的前面两个(lt表示序号小于)再加上label对象
合并成一个jQuery对象。
.css('border','none')
.css('borderBottom','solid 1px
navy')
.css({'width':'30px'});
以上三行代码都是针对之前的jQuery对象设置CSS样式,
如果一次需要设置多个CSS值,可用另一种形式,如:
.css
({'border':'none','borderBottom':'solid 1px navy','width':'30px'});
css()函
数如果只传一个字符串参数,则为取样式值,比如css('color')为取得当前jQuery对象的样式属性
color的值。jQuery 对象有多种这样的函数,比如,val('')为设value,val()为取value,text
('text')为设innerText,text() 为取得innerText,此外还有html(),用于操作innerHTML,而click
(fn)/click(),change(fn) /change()……系统函数则为事件的设置处理函数与触发事件。
由于多数
jQuery对象的方法仍返回当前jQuery,所以jQuery代码通常写成一串串的,如上面的
.css
('border','none')
.css('borderBottom','solid 1px navy')
.css
({'width':'30px'});
,而不需要不断重复定位对象,这是jQuery的链式特点,后面文章还会有
补充。
referrence:http://docs.jquery.com/Selectors
下篇:
href="http://www.jqueryajax.com/?p=175" target="_self">jQuery入门之(3)-选择器