2011-12-15 44 views
0

的問題:當我克隆 <div id="#cloneme1">...</div>我得到 <div id="cloneme2">...</div>但.keyup()函數不會讀取新的DOM元素jQuery的克隆元素,改變ID,然後在使用的keyup()不工作

$('#btnAdd').click(function() { 
     var num= $('.clonedInput').length; // how many "duplicatable" input fields we currently have 
     var newNum= new Number(num + 1);  // the numeric ID of the new input field being added 

     // create the new element via clone(), and manipulate it's ID using newNum value 
     var newElem = $('#cloneme' + num).clone().attr('id', 'cloneme' + newNum); 

     // manipulate the name/id values of the input inside the new element 
     newElem.children(':first').attr('id', 'alteredguianswer' + newNum) 

     // insert the new element after the last "duplicatable" input field 
     $('#cloneme' + num).after(newElem); 
    }); 

    $('input[type="text"]').keyup(function(){ 
       var id = $(this).attr("id"); // variable id = id of current textfield 
       var value=$(this).val(); // variable value = value in current textfield 
       $("#someplace"+id).text(value); // edit text elsewhere on page using value 
      }); 


<div> 
    <input type="button" id="btnAdd" value="add another name" /> 
</div> 
    <div id="cloneme1" style="margin-bottom:4px;" class="clonedInput">Question:<input type="text" id="guianswer1" value="Answer 1" /></div> 

我不瞭解如何獲得讀取新克隆元素的函數

回答

1

您正在綁定DOM中所有匹配元素的鍵控事件,但不是將來的元素。

如果你正在使用jQuery 1.7或更高版本,請嘗試使用

$('input[type="text"]').on('keyup', function(){ 
    var id = $(this).attr("id"); // variable id = id of current textfield 
    var value=$(this).val(); // variable value = value in current textfield 
    $("#someplace"+id).text(value); // edit text elsewhere on page using value 
}); 

如果您使用的是較早的版本,請嘗試使用現場

$('input[type="text"]').live('keyup', function(){ 
    var id = $(this).attr("id"); // variable id = id of current textfield 
    var value=$(this).val(); // variable value = value in current textfield 
    $("#someplace"+id).text(value); // edit text elsewhere on page using value 
}); 
+0

驚人的意見!完美工作,我知道如果升級到更新版本的jquery,該怎麼辦。 – user1082764 2011-12-15 05:28:59

0

您只將keyup處理程序分配給定義處理程序時存在的元素。這就像要求空房子裏的每個人吃晚飯,然後想知道爲什麼每個人在一個小時後回家時仍然飢腸轆轆。

您可能需要處理程序分配給每個克隆的元素:

var keyupHandler = function() { ... }; 
$('#btnAdd').click(function() { 
    ... 
    newElem.keyup(keyupHandler); 
} 

或者你需要充分利用的jQuery做對你來說,通過使用on代替keyup

$(document).on('keyup', 'input[type="text"]', function() { ... }); 

後一種形式將捕捉所有匹配存在選擇器的元素或將在後面存在