jQuery移除指定元素后的所有元素


jQuery 遍歷的nextAll() 方法可以搜索 DOM 樹中的元素跟隨的同胞元素,也就是一個元素后面的所有同級元素,刪除可以使用方法remove(),所以連起來為

$(selector).nextAll(“條件”).remove();

下面給出實例演示:點擊按鈕后,刪除被選項目之后的所有選項

  1. 創建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>
  2. 簡單設置一下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;}
  3. 編寫jquery代碼

    $(function(){
    $("input:button").click(function() {
    $("input:checkbox:checked").next().nextAll().remove();
    });
    })
  4. 觀察顯示效果

  • 選擇項目

  • 點擊刪除按鈕,被選項之后的所有同級元素都被刪除


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM