2014-06-20 64 views
0

我有一個表單部分處理名爲options的文本輸入。單擊上次現有輸入時添加輸入文本字段(使用jquery)

默認情況下,我提供了兩個選項。當最後一個點擊時,我想添加一個選項字段。

<input type='text' name='options[]' class='options'> 
<br/> 
<br/> 
<input type='text' name='options[]' class='options'> 

我試圖

$(".options:last").click(function(){ 
    $("#options").append("<br/><br/><input type='text' name='options[]' class='options'>"); 
}) 

它不工作的第一次。但之後不起作用。它不考慮jQuery添加的輸入。所以只有當我點擊第二個選項時纔有效。不是jquery添加的最後一個。怎麼做?

回答

1

click()方法僅結合事件處理程序來匹配當前存在於DOM元件。

由於新的文本框之後動態添加,因此它們沒有單擊處理程序。您必須手動綁定點擊處理程序(,效率很低),或者通過將事件處理程序綁定到靜態父元素來使用event delegation

假設#options是靜態的容器元素,因爲要追加到它,

可以使用.on()方法如下

$('#options').on('click','.options:last',function(){ 
$(this).after("<br/><br/><input type='text' name='options[]' class='options'>"); 
}) 
+0

好了,其他答案是更好的,我想。 –

0

您正在動態添加元素。它不會在第一次追加後獲取最後一個元素。

所以使用事件代表團使用.on()代碼 - Reference

您可以使用$('#options')委託$(document)吧,如果#options元素是靜態的。

$(document).on('click','.options:last',function(){ 
    $("#options").append("<br/><br/><input type='text' name='options[]' class='options'>"); 
}) 
0

你只需要點擊綁定甚至委託事件處理程序,以它使用.on來動態添加元素,如下所示:

$(document).on("click",".options:last",function(){ 
    $("#options").append("<br/><br/><input type='text' name='options[]' class='options'>"); 
}) 
0

您需要將函數綁定到添加元素後再次發生該事件。這樣做的

可能的方式將是

function AppendToEnd() 
{ 
    $("#options").append("<br/><br/><input type='text' name='options[]' class='options'>"); 
    $(".options:last").click(AppendToEnd()); // this will bind the function to the last element as before. 
}  

此外,您還需要事件最初自己綁定,所以加

$(".options:last").click(AppendToEnd()); 

在您當前的代碼。

0

您想要解除其他之前添加的輸入的點擊事件,因爲用戶可能想要在編輯它們之後對其進行編輯,這會導致添加不需要的選項。

此外,你可能會考慮將選項封裝在帶有ID的div中,因爲使用ID選擇器比使用類選擇器快得多。沒有,我存儲所選對象的負載,我不需要以後調用它,我可以重用我已經選擇的對象,並節省不必要的計算時間。

HTML

<div id="option-wrapper"> 
<input type='text' name='options[]' class='options' /> 
<br/> 
<br/> 
<input type='text' name='options[]' class='options' /> 
</div> 

JS

var wrapper = $("#option-wrapper"), 
bindClickEvents = function() { 
    var options = $(".options",wrapper); 
    options.unbind("click"); 
    options.last().on("click", function() { 
     $(this).after("<br/><br/><input type='text' name='options[]' class='options'>"); 
     bindClickEvents(); 
    }); 
}; 
bindClickEvents(); 

JS提琴:http://jsfiddle.net/JKurcik/HRg9M/

相關問題