簡體   English   中英

jQuery不刪除添加的元素

[英]JQuery not removing added element

我要做的是添加和刪除列表項。 我已將其添加到列表中,並且可以刪除現有項,但不能刪除已添加的項。 似乎可以,但是不行。 任何幫助,將不勝感激! 這里的代碼:

JQuery的:

<script  type="text/javascript">
$(function(){
    $('a#add').click(function(){
        $('<li><a href="#" id="remove">--</a>List item</li>').appendTo('ul#list');
    });

    $('a#remove').click(function(){ 
        $(this).parent().remove();
    });
});
</script>

HTML:

<a href="#" id="add">Add List Item</a>
<ul id="list">
<li><a href="#" id="remove">--</a> List item</li>
<li><a href="#" id="remove">--</a> List item</li>
<li><a href="#" id="remove">--</a> List item</li>
<li><a href="#" id="remove">--</a> List item</li>
</ul>

代碼的問題不僅僅是缺少唯一的id值-盡管應該使用一類'remove'-主要問題是新添加的項目沒有與之關聯的點擊處理程序。 在創建任何新項目之前,將執行添加單擊處理程序的代碼。

應該研究live()方法的使用-在這方面,我無法提供更多建議,因為我還不需要自己使用它。

干得好:

jQuery(function($) {
    $('#add').click(function(e) {
        $('<li><a href="#" class="remove">--</a>List item</li>').appendTo('#list');
        e.preventDefault();
    });

    $('.remove').live('click', function(e) { 
        $(this).parent().remove();
        e.preventDefault();
    });
});

嘗試這個

$('a#remove').live('click',function(){ 
        $(this).parent().remove();
    });

要么

  $('a#remove').live('click',function(){ 
            $(this).remove();
        });

忽略元素應該具有唯一ID屬性這一事實,始終要記住一件事:將函數綁定到事件時,例如$(selector).bind('click', function)$(selector).click(function) -只有DOM中與特定時間點的選擇器匹配的元素才會表現出預期的效果。 如果添加了選擇在稍后的時間相匹配的更多元素,這些不會神奇地獲得與期望的行為有關。

這是live() jQuery函數存在的原因之一,我鼓勵您看一下。 另一種方法是將所需的功能手動綁定到添加到DOM中的元素(如Felix所示)。

id屬性應該是唯一的,您的HTML無效,因此jQuery無法正常工作(我敢打賭a#remove選擇器只會選擇第一項)。 使用其他東西,例如name ,這不應該是唯一的。 另外,您可能想使用.parent("li") 這是我的處理方式:

jQuery的:

<script  type="text/javascript">
function setEvents() {
    $("a#add").click(function() {
        $("#list").append(
            $("<li>").append(
                $('<a href="#" name="remove">--</a>').click(removeItem)
            ).append("List item")
        );
    });

    $('a[name=remove]').click(removeItem);
}
function removeItem(e) {
    $(this).parent("li").remove();
}
$(document).ready(setEvents);
</script>

HTML:

<a href="#" id="add">Add List Item</a>
<ul id="list">
<li><a href="#" name="remove">--</a> List item</li>
<li><a href="#" name="remove">--</a> List item</li>
<li><a href="#" name="remove">--</a> List item</li>
<li><a href="#" name="remove">--</a> List item</li>
</ul>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM