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

jquery学习手记(4)元素的选择与操作

2013-08-02 11:32 453 查看
一.选择元素


id选择器,示例为:

1//SelectingelementsbyID
2$("#myId");//noteIDsmustbeuniqueperpage


类名选择器,示例为:

1//Selectingelementsbyclassname
2$(".myClass");


属性选择器,示例为:

1//Selectingelementsbyattribute
2$("input[name='first_name']");//beware,thiscanbeveryslowinolderbrowsers


复杂css选择器,示例为:

1//SelectingelementsbycompoundCSSselector
2$("#contentsul.peopleli");


伪选择器,示例为:

//Pseudo-selectors
$("a.external:first");
$("tr:odd");
//selectallinput-likeelementsinaform(moreonthisbelow)
$("#myForm:input");
$("div:visible");
//allexceptthefirstthreedivs
$("div:gt(2)");
//allcurrentlyanimateddivs
$("div:animated");


注意:

1.伪选择器使用
:visible
:hidden时,jquery只是测试此元素的真实可见性,而不是css的可见性或者呈现。jquery用来检测此元素在页面的物理高度和宽度是否都大于0.


2.这种测试不能和<tr>一起使用。当和<tr>一起使用时,jquery检查css的呈现属性,当呈现属性被设置为none的时候,该元素会被隐藏。

3.元素没有加入到DOM上的都视为不可见的。即使css设置元素的属性为可见,也不起作用。

二.选择选择器。

jquery提供了许多基于属性的选择器,这些选择器允许使用简单的规则表达式(基于任意属性的内容)来选择。示例如下:

1//findall<a>swhoserelattribute
2//endswith"thinger"
3$("a[rel$='thinger']");


测试元素是否存在:

1//Testingwhetheraselectioncontainselements
2if($("div.foo").length){
3...
4}


保存元素:

var$divs=$("div");


重新定义和过滤元素:

1//Refiningselections
2$("div.foo").has("p");//div.fooelementsthatcontain<p>tags
3$("h1").not(".bar");//h1elementsthatdon'thaveaclassofbar
4$("ulli").filter(".current");//unorderedlistitemswithclassofcurrent
5$("ulli").first();//justthefirstunorderedlistitem
6$("ulli").eq(5);//thesixth


选择表单元素:

注意:为了浏览器有更好的性能,使用
[type="element"]
而不是
:
element
伪选择器.

:button

1//:buttonpseudo-selector
2//selects<button>elementsandelementswithtype="button"
3$("form:button");


:checkbox

1//:checkboxpseudo-selector
2//selectselementswithtype="checkbox"
3$("form:checkbox");


:checked

1//:checkedpseudo-selector
2//selectscheckedcheckboxesandradiobuttons
3$("form:checked");


:disabled

1//:disabledpseudo-selector
2//selectsallinputelementswiththedisabledattribute
3$("form:disabled");


:enabled

1//:enabledpseudo-selector
2//selectsallelementsthatdonothavethedisabledattribute
3$("form:enabled");


:file

1//:filepseudo-selector
2//selectsallinputswithatype="file"
3$("form:file");


:image

1//:imagepseudo-selector
2//selectsallinputelementsoftype"image"
3$("form:image");


:input

//:inputpseudo-selector
//selects<input>,<textarea>,<select>,and<button>elements
$("form:input");


:password

1//:passwordpseudo-selector
2//targetsany[code]<input>
swithatypeofpassword
3$("form:password");[/code]

:radio

//:radiopseudo-selector
//selectsall<input>softype"radio"
$("form:radio");


1//Selectionassociatedradiobuttonswith:radio
2//selectsallradiobuttonswiththenameattributeofgender
3$("forminput[name="gender"]:radio")


:reset

//:resetpseudo-selector
//selectsallelementsoftype"reset"
$("form:reset");


:selected

//:selectedpseudo-selector
//selectsallselecteditemsin<option>elements
$("form:selected");


:submit

//:submitpseudo-selector
//selectsallinputswithtype="submit"
$("form:submit");


:text

//:textpseudo-selector
//selectsallinputswithtype="text"
$("form:text");


使用选择表达式

get/set方法

1//The$.fn.htmlmethodusedasasetter
2$("h1").html("helloworld");
3
4//Thehtmlmethodusedasagetter
5$("h1").html();


Set方法返回一个jquery对象,允许你在选择表达式中继续调用jquery方法。

Get方法根据你要求返回的结果,因此就不能在get方法的返回值中继续调用jquery方法。

例如:

//AttemptingtocallajQuerymethodaftercallingagetter
//ThiswillNOTwork
$("h1").html().addClass("test")


链式结构

如果你使用的选择表达式返回的是jquery对象,那么你就可以继续调用jquery对象的方法而不用使用分号作为中止符号,这种形式就像一个链条一样:

//Chaining
$("#content").find("h3").eq(2).html("newtextforthethirdh3!");


但通常为了可读性而把上述选择表达式拆分成如下形式:

1//Formattingchainedcode
2$("#content")
3.find("h3")
4.eq(2)
5.html("newtextforthethirdh3!");


同样jquery也提供了一个方法在链式表达式中间返回对象:
$.fn.end
。例如:


1//Restoringyouroriginalselectionusing$.fn.end
2$("#content")
3.find("h3")
4.eq(2)
5.html("newtextforthethirdh3!")
6.end()//restorestheselectiontoallh3sin#content
7.eq(0)
8.html("newtextforthefirsth3!");


操作元素

操作元素的get/set属性方法

$.fn.html–获取或者设置html内容.

$.fn.text-获取或者设置text内容;HTMLwillbestripped.

$.fn.attr-获取或者设置属性值.

$.fn.width–获取或者设置宽度.

$.fn.height-获取或者设置高度

$.fn.position–获取位置,仅有一个get方法。

$.fn.val–获取或者设置表单元素的值.

注意:选择表达式可能会影响所有的元素,如果仅要修改一个元素,请注意使用正确的表达式。例如:

//ChangingtheHTMLofanelement

$("#myDivp:first").html("New<strong>first</strong>paragraph!");


移动/复制/移除元素

移动元素

在DOM中移动元素的方法很多,通常使用的方法有两种:

放置一个选定的元素以另一个元素为坐标。

放置一个元素以选定元素为坐标。

例如:jquery提供的
$.fn.insertAfter
$.fn.after
方法。


$.fn.insertAfter
方法放置选定元素在参数中提供的元素位置之后。


$.fn.after
方法放置元素位于参数中提供的选定元素之后。


其他别的方法还有:

$.fn.insertBefore
/
$.fn.before
,
$.fn.appendTo
/
$.fn.append
,and
$.fn.prependTo
/
$.fn.prepend
.

实例如下:

1//Movingelementsusingdifferentapproaches
2
3
4
5//makethefirstlistitemthelastlistitem
6
7var$li=$("#myListli:first").appendTo("#myList");
8
9
10
11//anotherapproachtothesameproblem
12
13$("#myList").append($("#myListli:first"));
14
15
16
17//notethatthere'snowaytoaccessthe
18
19//listitemthatwemoved,asthisreturns
20
21//thelistitself


复制元素

//Makingacopyofanelement

//copythefirstlistitemtotheendofthelist

$("#myListli:first").clone().appendTo("#myList");


注意:如果你需要复制相关的数据及事件,请给
$.fn.clone
传递true参数。




移除元素

从页面移除元素的方法有两种:
$.fn.remove
$.fn.detach


$.fn.remove
一次性永久移除元素所有的数据和事件。


$.fn.detach
保留元素的数据和事件,可以恢复。




如果你仅向移除一个元素的内容而在此页面上保留这个元素,请使用$.fn.empty来舍弃元素的内部html。




创建新元素

Jquery使用
$()
来创建一个新的元素。示例如下:


//CreatingnewelementsfromanHTMLstring

$("<p>Thisisanewparagraph</p>");

$("<liclass=\"new\">newlistitem</li>");

//Creatinganewelementwithanattributeobject

$("<a/>",{

html:"Thisisa<strong>new</strong>link",

"class":"new",

href:"foo.html"

});


当新建一个元素时,通常不能离开就增加到页面上。如果想立即把一个元素加入到页面,可以使用如下的方法:




//Gettinganewelementontothepage

var$myNewElement=$("<p>Newelement</p>");

$myNewElement.appendTo("#content");

$myNewElement.insertAfter("ul:last");//thiswillremovethepfrom#content!

$("ul").last().after($myNewElement.clone());//clonethepsonowwehave2




或者不使用引用来保存元素:


//Creatingandaddinganelementtothepageatthesametime

$("ul").append("<li>listitem</li>");[code]


批量添加元素的方法,为了性能的考虑,请使用array来收集所有的元素,然后把它们一起加入到页面,例如:


varmyItems=[];

var$myList=$("#myList");

for(vari=0;i<100;i++){

myItems.push("<li>item"+i+"</li>");

}

$myList.append(myItems.join(""));


操作属性

操作属性的示例如下:

//Manipulatingasingleattribute

$("#myDiva:first").attr("href","newDestination.html");

//Manipulatingmultipleattributes

$("#myDiva:first").attr({

href:"newDestination.html",

rel:"super-special"

});

//Usingafunctiontodetermineanattribute'snewvalue

$("#myDiva:first").attr({

rel:"super-special",

href:function(idx,href){

return"/new/"+href;

}

});

$("#myDiva:first").attr("href",function(idx,href){

return"/new/"+href;

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: