2017-01-19 144 views
0

我的腳本有問題。我想創建動態對象,如果我推動「創建新元素」,新的對象將被創建,但如果我推進刪除,它不起作用。爲什麼?謝謝。Jquery創建新元素,但不會刪除此元素後

<!doctype html> 
 
    <html> 
 
    <meta charset="utf-8"> 
 
    <head> 
 
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
 
    <script> 
 
\t $(document).ready(function() { 
 
\t 
 
\t \t // Create new Object inside of #content 
 
\t \t $("#wrapper > #taskbar > #create_new_element").click(function(){ 
 
\t \t \t $("#wrapper > #content").append('<div class="new_object"><p>New Object</p><a class="remove_object">Remove</a></div>'); 
 
\t \t }); 
 
\t 
 
\t \t // Remove an Object inside of #content 
 
\t \t $("#wrapper > #content > .new_object > .remove_object").click(function(){ 
 
\t \t \t $(this).closest('<div class="new_object"><p>New Object</p><a class="remove_object">Remove</a></div>').remove(); 
 
\t \t }); 
 
\t }); 
 

 
    </script> 
 
    </head> 
 
    <body> 
 
    <div id="wrapper"> 
 

 
\t 
 
\t \t <div id="taskbar"> 
 
\t \t \t <p id="create_new_element">Create new Element</p> 
 
\t \t </div> 
 
\t \t 
 
\t \t <div id="content"></div> 
 

 

 

 
    </div> 
 
    </body>

+0

的http://計算器。 com/questions/19129794/how-to-remove-an-element-that-is-added-dynamically-in-javascript –

+0

'在動態div上添加eventlistener'看看SOs js top100的問題... –

+0

可能重複[如何刪除在javascript中動態添加的元素](http://stackoverflow.com/questions/19129794/how-刪除一個元素,那是動態添加在javascript中) – ppasler

回答

2

你必須使用.on方法動態創建的元素。

$(document).on('click',"#wrapper > #content > .new_object > .remove_object",function(){ 
    $(this).closest('.new_object').remove(); 
}); 

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

瞭解更多關於event delegation

+1

我在jsfiddle中試過這個,它向我拋出一個錯誤'未捕獲的錯誤:語法錯誤,無法識別的表達式:

New Object

Remove
'。我不得不在'.closest()'裏面定義'.new_object'類來使其工作:https://jsfiddle.net/cg4ouyrm/1/。我想我一定在做錯事。從我+1仍然=) –

+0

你是對的。謝謝你的觀點! –

0

你事件綁定到新創建的元素創建後,他們

檢查下面的代碼片段

$(document).ready(function() { 
 

 
    // Create new Object inside of #content 
 
    $("#wrapper > #taskbar > #create_new_element").click(function() { 
 
    $("#wrapper > #content").append('<div class="new_object"><p>New Object</p><a class="remove_object">Remove</a></div>'); 
 
    bindRemoveEvent(); 
 
    }); 
 

 
    function bindRemoveEvent() { 
 
     $(".remove_object").on('click', function() { 
 
     // console.log(this); 
 
     $(this).closest('.new_object').remove(); 
 
     }); 
 
    } 
 
    // Remove an Object inside of #content 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 

 
<body> 
 
    <div id="wrapper"> 
 

 

 
    <div id="taskbar"> 
 
     <p id="create_new_element">Create new Element</p> 
 
    </div> 
 

 
    <div id="content"></div> 
 

 

 

 
    </div> 
 
</body>

希望這有助於