【问题标题】:Get input field contents and append to HTML <div> element获取输入字段内容并附加到 HTML <div> 元素
【发布时间】:2014-07-17 16:04:24
【问题描述】:

我正在尝试获取输入字段的内容并将它们添加到我的 HTML 文档中。

这是我所拥有的,但它还不起作用:

            <!DOCTYPE html>
    <html>
        <head>
            <title>To Do</title>
            <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
            <script type="text/javascript" src="script.js"></script>
        </head>
        <body>
            <h2>To Do</h2>
            <form name="checkListForm">
                <input type="text" name="checkListItem"/>
            </form>
            <div id="button">Add!</div>
            <br/>
            <div class="list"></div>
        </body>
    </html>

            $(document).ready(function(){
        var input = $("input[name=checkListItem]");
        $("button").click(function(){
    $("#button").click(function(){   

var toAdd = $('input[name=checkListItem]').val();
    });
            $(".list").append('<div class="item">' + toAdd + '</div>');
        });
    });

谁能告诉我我做错了什么,好吗?

谢谢!

【问题讨论】:

  • toAdd 更改为$(input).val()
  • 你的编辑真的把代码搞砸了@user3472810
  • 呃。不,我刚刚意识到我在原来的帖子中遗漏了一些东西。无论如何,它没有工作。对不起! jQuery初学者!非常感谢您的帮助!

标签: jquery input append


【解决方案1】:

你有几个错误:

1) $("button") 应该是 $("#button")

2) $("input[name=checkListItem]") 应该是 $("input[name='checkListItem']")

3) 将 var input = $("input[name='checkListItem']").val(); 放入 click 事件

然后这样做:

$(document).ready(function(){

    $("#button").click(function(){

       var input = $("input[name='checkListItem']").val(); 
       // .val() will give textbox value

       $(".list").append('<div class="item">' + input + '</div>');
     });

});

Fiddle Example

或更简单地说:

$(document).ready(function(){

   $("#button").click(function(){

    $(".list").append('<div class="item">' + $("input[name='checkListItem']").val()+ '</div>');

   });

});

【讨论】:

  • 非常感谢!它现在正在工作!我一直在通过添加/更改内容以使其正常工作来搞砸它。谢谢!
  • @user3472810 只要理解它然后使用它你就会知道它是如何完成的
【解决方案2】:
$(document).ready(function(){
    var input = $("input[name=checkListItem]").val();
    $("#button").click(function(){
        $(".list").append('<div class="item">' + input + '</div>');
    });
});

button是一个div,不是html元素,所以加#

【讨论】:

  • 在您的代码中input 已经是一个jQuery 对象,无需再次将其包装在$() 中以获取值
猜你喜欢
  • 1970-01-01
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多