将输入值附加到div

时间:2012-03-14 19:14:45

标签: javascript jquery

有人可以告诉我如何获取输入值并在用户点击添加链接后将其附加到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;
                });

这会创建另一个输入字段;我只想要一个输入框,让用户单击添加,然后它获取该值,将其放入列表,并清除输入框,以便用户可以再次添加其他内容。

5 个答案:

答案 0 :(得分:4)

使用jQuery的append()函数

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

这是a working fiddle


警告:以下意见

在创建存储jQuery对象的变量时,我认为使用$为变量添加前缀是有帮助的。这样,您就知道您正在使用jQuery对象。它还使那些来到你身后的人更容易识别你在做什么:

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

答案 1 :(得分:0)

类似的东西:

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

更改

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

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

val()方法给出了input元素的值,你不能在一个会抛出错误的字符串上调用jQuery方法。

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

答案 4 :(得分: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--;
                });     
        });