[英]Append li to parent ul
我正在嘗試使用jquery從輸入中獲取文本以添加到父級中的現有ul,但是當我這樣做時:
$("input[type = 'text']").keypress(function(event){
if(event.which === 13){
//grabbing new todo from input
var todoText = $(this).val();
$(this).val("");
//create a new li and add to ul
$(this).parent().append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
}
});
它直接向父級添加了一個新li。 我意識到我忘了提到我希望將其添加到現有的ul中,因此我嘗試更改此設置:
//create a new li and add to ul
$(this).parent("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
但它仍然無法正常工作,現在甚至都沒有在任何地方添加任何內容。 也許是因為我語法錯誤或其他原因?
這是我的玉的結構示例:
.frame
.bit-2
h1
| text
i.fa.fa-plus
input(type='text', placeholder='text')
ul
li
span
i.fa.fa-trash
| text
li
span
i.fa.fa-trash
| text
有什么想法嗎?
請使用.next()函數,如下所示。
$(document).ready(function(){
$("input[type = 'text']").keypress(function(event){
if(event.which === 13){
//grabbing new todo from input
var todoText = $(this).val();
$(this).val("");
//create a new li and add to ul
$(this).next("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
}
});
});
對於演示,請檢查以下片段。
$(document).ready(function(){ $("input[type = 'text']").keypress(function(event){ if(event.which === 13){ //grabbing new todo from input var todoText = $(this).val(); $(this).val(""); //create a new li and add to ul $(this).next("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"/> <ul><li>First</li></ul>
也許這會工作
$(this).closest("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.