定義和用法
end() 方法結束當前鏈條中的最近的篩選操作,並將匹配元素集還原為之前的狀態。
以上是官方說法,比較難理解。
還是用一個例子來說明
<!DOCTYPE html> <html> <head> <style>p { margin:10px; padding:10px; }</style> <script type="text/javascript" src="/jquery/jquery.js"></script> </head> <body> <p><span>Hello</span>, how are you?</p> <script>$("p").find("span").end().css("border", "2px red solid");</script> </body> </html> $("p").find("span")表示查找P元素下的SPAN元素 但是我想更改P的邊框,這時我就要返回到P元素(即從SPAN返回到P,就是還原為之前的狀態) $("p").find("span").end()這個語句就返回來了。 $("p").find("span").end().css("border", "2px red solid")把P的邊框設置了。 ------------------- 對於end()方法,jQuery文檔是這樣解釋的:jQuery回到最近的一個"破壞性"操作 之前。即: 將匹配的元素列表變為前一次的狀態。 但給的例子並不是很明顯,相信不少人並沒有理解它的用法。 下邊我們以一個非常簡單的例子來說明下用法,html代碼如下: <div id="test"> <h1>jQuery end()方法</h1> <p>講解jQuery中end()方法。</p> </div> JS代碼: $(document).ready(function() { $("#test").click(function() { $(this).find("p").hide().end().hide(); }); });
點擊id為test的div時,首先找到div里邊的p標簽,將其隱藏。接下來使用end()方法結束了對p標簽的引用,此時返回的是#test(jQuery對象),從而后邊的hide()方法隱藏了div。這樣相信大家已經理解了jQuery中end()方法。
---------------------- <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> <!-- $(function(){ $('<input type="button" value="click me" /><input type="button" value="triggle click me" /><input type="button" value="detach handle" /><input type="button" value="show/hide text" />').appendTo($('body')); $('input[type="button"]').eq(0).click(function(){ alert('you clicked me!'); }) .end().eq(1).click(function(){ $('input[type="button"]:eq(0)').trigger('click'); }) .end().eq(2).click(function(){ $('input[typw="button"]:eq(0)').unbind('click'); }) .end().eq(3).toggle(function(){ $('.panel').hide('slow'); },function(){ $('.panel').show('slow'); }); }) //--> </script> <style type="text/css"> .panel{ padding:20px; color:#FFFFFF; font-weight:bold; width:200px; height:50px; } </style> <div class="panel">welcome to jQuery!</div>