$(".delete").click(function () {
$(".delete").parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="taskCont">
<div class="todoCont">
<h2>todo</h2>
<div class="tasks" id="tasks">
<input type="checkbox" id="checkBox">
<div class="cat_time">
<h3 id="getCategory" class="getCategory">Coding</h3>
<p id="getTime">12:30 AM</p>
</div>
<span id="getDescription">Practice Javascript</span>
<p class="delete">Delete</p>
</div>
</div>
<div class="completedTaskCont">
<h2>completed</h2>
<div class="tasks">
<input type="checkbox" id="checkBox" checked>
<div class="cat_time">
<h3 id="getCategory">Shopping</h3>
<p id="getTime">10:30 AM</p>
</div>
<span id="getDescription">Bazar India</span>
<p class="delete">Delete</p>
</div>
</div>
</div>
在此代码中,当我单击删除时,它将全部删除。如何解决这个问题? 这是一个待办事项清单代码。我试图解决使用for循环的问题,但是没有用。
答案 0 :(得分:6)
使用以下内容:
$(".delete").click(function () {
// This will delete the parent of element being clicked
$(this).parent().remove();
});
$(".delete").click(function () {
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="taskCont">
<div class="todoCont">
<h2>todo</h2>
<div class="tasks" id="tasks">
<input type="checkbox" id="checkBox">
<div class="cat_time">
<h3 id="getCategory" class="getCategory">Coding</h3>
<p id="getTime">12:30 AM</p>
</div>
<span id="getDescription">Practice Javascript</span>
<p class="delete">Delete</p>
</div>
</div>
<div class="completedTaskCont">
<h2>completed</h2>
<div class="tasks">
<input type="checkbox" id="checkBox" checked>
<div class="cat_time">
<h3 id="getCategory">Shopping</h3>
<p id="getTime">10:30 AM</p>
</div>
<span id="getDescription">Bazar India</span>
<p class="delete">Delete</p>
</div>
</div>
</div>
答案 1 :(得分:3)
独自上课是很危险的。取“这个”:
$(".delete").click(function () {
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="taskCont">
<div class="todoCont">
<h2>todo</h2>
<div class="tasks" id="tasks">
<input type="checkbox" id="checkBox">
<div class="cat_time">
<h3 id="getCategory" class="getCategory">Coding</h3>
<p id="getTime">12:30 AM</p>
</div>
<span id="getDescription">Practice Javascript</span>
<p class="delete">Delete</p>
</div>
</div>
<div class="completedTaskCont">
<h2>completed</h2>
<div class="tasks">
<input type="checkbox" id="checkBox" checked>
<div class="cat_time">
<h3 id="getCategory">Shopping</h3>
<p id="getTime">10:30 AM</p>
</div>
<span id="getDescription">Bazar India</span>
<p class="delete">Delete</p>
</div>
</div>
</div>
因为您写的内容告诉页面删除所有“ .delete”的父级,而您只希望单击元素($(this))。
答案 2 :(得分:0)
您正在调用delete
类的所有元素,并对所有元素执行链接的操作。另一种可能的语法是调用click event
对象上的目标元素:$(event.target).parent().remove()
。