[英]Remove <li> element from <ul> onclick without refreshing page
目前,我需要在單擊時刪除由 jQuery 創建的 li 元素。
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
var li = $('<li/>')
.onclick(function() {
$(this).remove()
})
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My New Pen!</title>
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<h1>What do you like?</h1>
<form id=likeform>
<input name=thing placeholder="a thing you like" size=30>
<input type=submit>
</form>
<ul id=likes></ul>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="scripts/index.js"></script>
</body>
</html>
目前這已經成功,除了我需要手動重新加載頁面以使更改生效
你的問題就在這里:
var li = $('<li/>').onclick(function() {
$(this).remove()
});
首先,您不需要比較運算符( <
, >
),因為 JQuery 將按標簽名稱選擇元素。 此外,您不能在動態創建的元素上以“正常”方式添加事件偵聽器。
這就是在這里討論的。
要解決您的問題,請將上述內容替換為:
$(document).on("click", "li", function() {
$(this).remove();
});
工作示例:
(function() { $(document).ready(function() { $("#likeform").submit(function(event) { var input = $(this).children("input[name='thing']") var thing = $(input).val() $("#likes").append("<li>" + thing + "</li>") $(input).val("") event.preventDefault() }) }) var li = $(document).on("click", "li", function() { $(this).remove(); }); }()) var listitems = document.getElementsByTagName("li") for (var i = 0; i < listitems.length; i++) { listitems[i].onclick = this.parentNode.removeChild((this)) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1>What do you like?</h1> <form id=likeform> <input name=thing placeholder="a thing you like" size=30> <input type=submit> </form> <ul id=likes></ul>
我認為這基本上就是你想要做的:
$('li').each(function (i) { $(this).click(() => $(this).remove()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <ul> <li>foo</li> <li>bar</li> </ul> </body>
請您嘗試以下。
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
$(document).on("click", "#likes li", function(){
$(this).remove();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.