jQuery入门[2]-选择器
jQuery入门[3]-事件
jQuery入门[4]-链式代码
jQuery入门[5]-AJAX
jQuery入门[6]-动画
JQuery优点
◦体积小(v1.2.3 15kb)
◦丰富的DOM选择器(CSS1-3 + XPath) ◦跨浏览器(IE6,FF,Safari,Opera)
◦链式代码
◦强大的事件、样式支持
◦强大的AJAX功能
◦易于扩展,插件丰富
jQuery的构造函数接收四种类型的参数:
- jQuery(expression,context)
- jQuery(html)
- jQuery(elements)
- jQuery(fn)
第一种根据表达式(ID,DOM元素名,CSS表达式,XPath表达式)找出文档中的元素,并组装成一个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 > jQuery basic </ title >
< style type ="text/css" >
.selected
{
background-color : Yellow ;
}
</ style >
< script src ="../scripts/jquery-1.2.3.intellisense.js" type ="text/javascript" ></ script >
</ head >
< body >
< h3 > jQuery构造函数 </ h3 >
< ul >
< li > jQuery(expression,context) </ li >
< li > jQuery(html) </ li >
< li > jQuery(elements) </ li >
< li > jQuery(fn) </ li >
</ ul >
< script type ="text/javascript" >
</ script >
</ body >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< title > jQuery basic </ title >
< style type ="text/css" >
.selected
{
background-color : Yellow ;
}
</ style >
< script src ="../scripts/jquery-1.2.3.intellisense.js" type ="text/javascript" ></ script >
</ head >
< body >
< h3 > jQuery构造函数 </ h3 >
< ul >
< li > jQuery(expression,context) </ li >
< li > jQuery(html) </ li >
< li > jQuery(elements) </ li >
< li > jQuery(fn) </ li >
</ ul >
< script type ="text/javascript" >
</ script >
</ body >
</ html >
将以下jQuery代码加入文末的脚本块中:
jQuery(
"
ul>li:first
"
).addClass(
"
selected
"
);
页面运行效果如下:
其中jQuery()可替换为快捷方式$(),如果$被其它对象占用,可使用jQuery.noConflict()函数取消快捷方式。
"ul>li:first"中ul>li表示所有位于ul下的li元素(为CSS表达式,XPath方式可用ul/li),:first表示其中的第一个。addClass()为jQuery对象用来添加CSS样式类的函数,相反的函数为removeClass()。
再加入以下代码:
$(
'
ul
'
).append($(
'
<li>new item</li>
'
));
运行效果如下:
其中$('<li>new item</li>')将其中的字符串转换为DOM对象,然后通过append()函数加入ul对象的最后。
接下来:
$(document).ready(
function
(){
$( ' ul ' ).css( ' color ' , ' red ' );
});
则效果如:
$( ' ul ' ).css( ' color ' , ' red ' );
});
jQuery构造函数中还可以真接传入DOM对象,如document,或jQuery对象(当然就没什么意义)。ready()函数为document添加事件处理函数,将ul的颜色设为红色。
$(document).ready()由于应用场景众多,所以可以直接用$(fn)来代替,fn表示处理函数。(ready处理函数貌似在文档内容载入完成后执行,无需等待相关其它图片等资源载入完成,所以比load事件要更早执行,对于这点,没有具体证实)
$(
function
(){
alert( ' welcome to jQuery ' );
});
以上代码的效果是页面一载入,就弹出一个对话框。
alert( ' welcome to jQuery ' );
});
reference:
http://docs.jquery.com/Core
http://docs.jquery.com/Selectors
--未完待续--