.remove()函数在jquery中不起作用



我想删除动态添加的div及其不起作用的部分。我尝试了所有的技术,但并不能解决这个问题。

var date = document.querySelector("#heading > h1");
var today = new Date();
var options = {
weekday: "long",
day: "numeric",
month: "long"
};
var day = today.toLocaleDateString("en-US", options);
date.innerHTML = day;

$("#newItem").click(function(){
var text = $("#itemAdder > input").val();
$("#itemAdder").before('<div class="item"><input type="checkbox"><p>' + text +'</p><span class="material-icons md-18 toDelete">delete</span></div>');
$("#itemAdder > input").val("");
});
$("span").on("click", function() {
$(this).find(".item").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="heading">
<h1></h1>
</div>
<div class="box">
<div class="item">
<input type="checkbox">
<p>Hello World</p>
<span class="material-icons md-18 toDelete">delete</span>
</div>

<div class="item" id="itemAdder">
<input type="text" placeholder="New Item" autocomplete="off">
<button id="newItem">+</button>
</div>
</div>
<br/>

它不起作用,因为您正在中搜索.item

$("span").on("click", function() { $(this).find(".item")

要做到这一点,你可以尝试$(this).parent().remove()

find((是jQuery中的一个内置方法,用于查找所选元素的所有子元素。它将一直遍历到DOM树中所选元素的最后一个叶子你应该使用
$(this).parent(".item").remove(); 

而不是

$(this).find(".item").remove();

最新更新