我的脚本有问题。我想创建动态对象,如果我按下“创建新元素”,将创建新对象,但如果我按下删除,它不起作用。为什么?谢谢。
<!doctype html>
<html>
<meta charset="utf-8">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(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>');
});
// Remove an Object inside of #content
$("#wrapper > #content > .new_object > .remove_object").click(function(){
$(this).closest('<div class="new_object"><p>New Object</p><a class="remove_object">Remove</a></div>').remove();
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="taskbar">
<p id="create_new_element">Create new Element</p>
</div>
<div id="content"></div>
</div>
</body>
最佳答案
您必须使用.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的信息.
关于javascript - Jquery创建新元素,但之后不会删除该元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41749821/