我正在从我的JavaScript添加带有文本的删除按钮的HTML。我想用它删除li和文本。
我认为我没有正确找到要删除的项目。
感谢任何帮助!
$("#add_btn").click(function() {
var job = $("#add_task").val().trim();
if (job.length != 0) {
$("#theList").append(
'<li>' + '<button id="remove_btn">Remove</button>' + job + '</li>'
);
} else {
window.alert("Don't add blank job");
}
});
$("#remove_btn").click(function() {
//intended to remove li and text...
$(this).next().remove(); //this is not working
});
以下是HTML:
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>To Do List</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="toDoList.js"></script>
</head>
<body>
<h1>To Do List</h1>
<label for="add_task">Add Task:</label>
<input type="text" id="add_task" name="add_task">
<br>
<button id="add_btn">
Add the task
</button>
<br>
<br>
<br>
<h2>My To Do List</h2>
<ol id="theList">
</ol>
</body>
</html>
答案 0 :(得分:3)
请勿在重复的地方使用id
。我正在使用一些更正来更新您的代码:
$("#add_btn").click(function() {
var job = $("#add_task").val().trim();
if (job.length != 0) {
$("#theList").append(
//----------------v---v: Change ID to Class. You are repeating. «««««
'<li>' + '<button class="remove_btn">Remove</button>' + job + '</li>'
);
} else {
window.alert("Don't add blank job");
}
});
// Delegate the event. «««««
$("#theList").on("click", ".remove_btn", function() {
//intended to remove li and text...
// Change to closest as the button is inside the `<li>` «««««
$(this).closest("li").remove(); // this will work
});
<强>段强>
$(function () {
$("#add_btn").click(function() {
var job = $("#add_task").val().trim();
if (job.length != 0) {
$("#theList").append(
//----------------v---v: Change ID to Class. You are repeating.
'<li>' + '<button class="remove_btn">Remove</button>' + job + '</li>'
);
} else {
window.alert("Don't add blank job");
}
});
// Delegate the event.
$("#theList").on("click", ".remove_btn", function() {
//intended to remove li and text...
// Change to closest as the button is inside the `<li>`
$(this).closest("li").remove(); // this will work
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1>To Do List</h1>
<label for="add_task">Add Task:</label>
<input type="text" id="add_task" name="add_task">
<br>
<button id="add_btn">
Add the task
</button>
<br>
<br>
<br>
<h2>My To Do List</h2>
<ol id="theList">
</ol>
&#13;