2012-03-14 85 views
1

有人可以告訴我如何獲取輸入值並在用戶點擊添加鏈接後將其附加到div上?將輸入值附加到div

這是我能做的最好的。 HTML:

<div id="customUtility-container"></div> 
<a href="#" id="addUtility">Add</a> 

的jQuery:

$(function() { 
       var addDiv = $('#customUtility-container'); 
       var i = $('#customUtility-container').size() + 1; 

       $('#addUtility').live('click', function() { 
         $('#customUtility').val().appendTo(addDiv); 
         $('<p><label for="customUtility-container"><input type="text" id="customUtility" size="20" name="customUtility_' + i +'" value="" placeholder="" /></label> <a href="#" id="removeUtility">Remove</a></p>').appendTo(addDiv); 
         i++; 
         return false; 
       }); 

       $('#removeUtility').live('click', function() { 
         if(i > 2) { 
           $(this).parents('p').remove(); 
           i--; 
         } 
         return false; 
       }); 

然而,這創建了另一個輸入字段;我只想要一個輸入框,讓用戶單擊添加,然後它將該值,放入列表中,並清除輸入框,以便用戶可以再次添加其他內容。

回答

0

我結束了再殺一切,重做:

$(function() { 
       var i = $('#customUtility-container').size() + 1; 
       $("#addUtility").on("click", function() { 
        $("#customUtility-container").append('<div id ="customUtility_' + i +' " name="customUtility_' + i +' ">'+ $("#customUtility").val() + '<a href="#customUtility-container" id="removeUtility">Remove</a></div>'); 
       }); 

       $('#removeUtility').live('click', function() { $(this).closest('div').remove(); 
               i--; 
       });  
     }); 
0

喜歡的東西:

addDiv.html(addDiv.html() + whateveryouwanttoadd) 
4

使用jQuery的append()功能

addDiv.append($('#customUtility').val()); 

這裏是a working fiddle


警告:以下

意見當創建一個變量來存儲一個jQuery對象,我認爲這是有幫助的有$前綴的變量。這樣,你就知道你正在使用一個jQuery對象。這也使得它更容易爲那些即將在你身後認識到自己在做什麼:

var $addDiv = $('#customUtility-container'); 
$addDiv.append($('#customUtility').val()); 
0
addDiv.append($('#customUtility').val()); 
0

變化

$('#customUtility').val().appendTo(addDiv); 

addDiv.append($('#customUtility').val()); 

val()方法給出的值輸入元素,你不能在一個會拋出錯誤的字符串上調用jQuery方法。

工作演示 - http://jsfiddle.net/t9D8R/