jQuery核心之DOM操作的常用方法
参考jQuery官网API文档
1、.attr()获取 :
$( "a" ).attr( "href" );
设置:
$( "a" ).attr( "href", "allMyHrefsAreTheSameNow.html" );$( "a" ).attr({title: "all titles are the same too!",href: "somethingNew.html"});
2、选择器的提取操作:
// Refining selections.$( "div.foo" ).has( "p" ); // div.foo elements that contain <p> tags$( "h1" ).not( ".bar" ); // h1 elements that don't have a class of bar$( "ul li" ).filter( ".current" ); // unordered list items with class of current$( "ul li" ).first(); // just the first unordered list item$( "ul li" ).last();$( "ul li" ).eq( 5 );
3、选择器与常用方法:
$( "h1" ).html( "hello world" );
$( "h1" ).html();
$( "h1" ).html().addClass( "test" );
链式调用:
$( "#content" ).find( "h3" ).eq( 2 ).html( "new text for the third h3!" );
.end()方法:
$( "#content" ).find( "h3" ).eq( 2 ).html( "new text for the third h3!" ).end() // Restores the selection to all h3s in #content.eq( 0 ).html( "new text for the first h3!" );
4、获取或设置元素的信息:g:获取,s设置
.html() ---- g&s
.text() ---- g&s
.attr() ---- g&s
.width() ---- g&s 单位 px,整数
.height() ---- g&s 单位 px,整数
.position() ---- g
.val() ---- g&s
移动,复制,删除元素方法:
移动元素:
B.insertAfter(A): B 在 A 之后
B.after(A) : B 在 A 之前 (B 后面跟着 A)
.insertBefore() 、.before()、appendTo()、append()、prependTo()、prepend()类似
区别:append、appendTo是在被选元素后面增加,prepend,prependTo是在被选元素的前面增加
append 与 prepend ,appendTo 与 prependTo返回的结果一致
// Make the first list item the last list item:
法1、$( "#myList" ).append( $( "#myList li:first" ) ); //返回结果是$( "#myList" )
法2、var li = $( "#myList li:first" ).appendTo( "#myList" ); //返回结果是 $( "#myList li:first" ) 这个元素。
复制元素:
// Copy the first list item to the end of the list:
$( "#myList li:first" ).clone().appendTo( "#myList" );
删除元素:
.remove() :永久删除(包括相关数据以及事件绑定),返回被删除的元素,如果将这个元素重新放回页面中(如:append),它将不包括之前有的任何相关数据以及事件绑定。
.detach( ) : 只是将元素从页面中移除(并不将其相关数据和事件绑定删除),返回被删除的元素,如果将这个元素重新放回页面中(如:append),它将和被删除之前一样。
var btn1;$("#1").on("click",function(){alert($(this).html());});$("#remove").on("click",function(){btn1 = $("#1").remove(); // 依次点击remove,back,1,将不会有任何东西alert});$("#back").on("click",function(){$("body").append(btn1);});$("#detach").on("click",function(){btn1 = $("#1").detach(); //依次点击detach,back,1将会弹出1});
创建:
// Creating new elements from an HTML string.$( "<p>This is a new paragraph</p>" );$( "<li class=\"new\">new list item</li>" );
再如:(因为class是保留字,所以要用引号)
// Creating a new element with an attribute object.$( "<a/>", {html: "This is a <strong>new</strong> link","class": "new",href: "foo.html"});
将其加到页面中:(append这种类型的操作是一种耗费资源的操作,如果数量特别多的元素需要这类操作,最好先将其放到一个数组,最后append,这样能节省资源,提高效率,最后别忘了将每个元素分隔出来)
var myItems = [];var myList = $( "#myList" );for ( var i = 0; i < 100; i++ ) {myItems.push( "<li>item " + i + "</li>" );}myList.append( myItems.join( "" ) );


浙公网安备 33010602011771号