优秀js开源框架-jQuery使用手册(1)

2020-05-19 07:38:27易采站长站整理

function jq(){
   $(“img”).each(function(){ 
        this.src = “2.jpg”; });
}
运行:当点击id为test的元素时,img标签的src都变成了2.jpg。
eq(pos)
说明:减少匹配对象到一个单独得dom元素
参数:pos (Number): 期望限制的索引,从0 开始
例子:
未执行jQuery前: 
<p>This is just a test.</p>
<p>So is this</p>
<a href=”#” id=”test” onClick=”jq()”>
jQuery</a>jQuery代码及功能: 
function jq(){
    alert($(“p”).eq(1).html())
}
运行:当点击id为test的元素时,alert对话框显示:So is this,即第二个<p>标签的内容
get() get(num)
说明:获取匹配元素,get(num)返回匹配元素中的某一个元素
参数:get (Number): 期望限制的索引,从0 开始
例子:
未执行jQuery前: 
<p>This is just a test.</p>
<p>So is this</p>
<a href=”#” id=”test” onClick=”jq()”>jQuery</a>
jQuery代码及功能: 
function jq(){
    alert($(“p”).get(1).innerHTML);
}
运行:当点击id为test的元素时,alert对话框显示:So is this,即第二个<p>标签的内容
注意get和eq的区别,eq返回的是jQuery对象,get返回的是所匹配的dom对象,所有取$(“p”).eq(1)对象的内容用jQuery方法html(),而取$(“p”).get(1)的内容用innerHTML
index(obj)
说明:返回对象索引
参数:obj (Object): 要查找的对象
例子:
未执行jQuery前: 
<div id=”test1″></div>
<div id=”test2″></div>
<a href=”#” id=”test” onClick=”jq()”>jQuery</a>
jQuery代码及功能: 
function jq(){
    alert($(“div”).index(document.getElementById(‘test1’)));
    alert($(“div”).index(document.getElementById(‘test2’)));
}
运行:当点击id为test的元素时,两次弹出alert对话框分别显示0,1
size()   Length
说明:当前匹配对象的数量,两者等价
例子:
未执行jQuery前: 
<img src=”test1.jpg”/>
<img src=”test2.jpg”/>
<a href=”#” id=”test” onClick=”jq()”>jQuery</a>
jQuery代码及功能: 
function jq(){
    alert($(“img”).length);