2016-08-05 84 views
0

我試圖從一個輸入獲得的文本使用jQuery添加到父現有的UL,但是當我這樣做:追加李父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>"); 
    } 
}); 

它直接增加了一個新的李書福父母。我意識到,我忘了提,我希望它被添加到現有的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    

發生了什麼事的任何想法?

+0

有你看在你的瀏覽器的開發工具修改HTML?文本可能被添加,但不是您認爲的地方。另外,如果您的Javascript中存在錯誤,則會通知您這個問題。 – Sablefoste

+0

輸入沒有父母ul,使用兄弟姐妹... –

+0

是的,我已經看了修改後的html。這就是我發現它沒有加入到ul中的原因。我也沒有得到任何錯誤。 –

回答

0

請使用。接下來()函數像下面。

$(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>

+0

非常感謝! –

-1

可能這會工作

$(this).closest("ul").append("<li><span><i class='fa fa-trash'></i></span> " + todoText + "</li>"); 
+0

UI不是文本框的父級,所以這不會附加到UL。 –

+0

對不起..我沒有看到結構(粗心)@RahulPatel – ubm

+0

它的好友。但結構已經在問題中了。 –

0

首先,如果你不想直接父,但一個父母,你應該使用closest代替parent

$(this).closest('ul') 

其次,在你發佈的結構中,UL看起來不是輸入的父母,而是兄弟姐妹,這意味着你可以用next

$(this).next('ul') 

但是,這是非常具體的,意味着輸入將永遠必須緊挨ul。
如果你知道它總是會在框架的背景下,我可能會喜歡的東西去:

$(this).closest('.frame').find('ul')