jQuery 遍歷的nextAll() 方法可以搜索 DOM 樹中的元素跟隨的同胞元素,也就是一個元素后面的所有同級元素,刪除可以使用方法remove(),所以連起來為
$(selector).nextAll(“條件”).remove();
下面給出實例演示:點擊按鈕后,刪除被選項目之后的所有選項
-
創建Html元素
<div class="box">
<span>點擊按鈕后,刪除被選項目之后的所有選項。</span><br>
<div class="content">
<input type="checkbox" name="item"><span>蘿卜</span>
<input type="checkbox" name="item"><span>青菜</span>
<input type="checkbox" name="item"><span>小蔥</span><br>
<input type="checkbox" name="item"><span>豆腐</span>
<input type="checkbox" name="item"><span>土豆</span>
<input type="checkbox" name="item"><span>茄子</span><br>
</div>
<input type="button" value="刪除">
</div> -
簡單設置一下css樣式
div.box{width:300px;height:200px;padding:10px 20px;border:4px dashed #ccc;}
div.box>span{color:#999;font-style:italic;}
div.content{width:250px;height:100px;margin:10px 0;border:1px solid green;}
input{margin:10px;}
input[type='button']{width:200px;height:35px;margin:10px;border:2px solid #ebbcbe;} -
編寫jquery代碼
$(function(){
$("input:button").click(function() {
$("input:checkbox:checked").next().nextAll().remove();
});
}) -
觀察顯示效果