简体   繁体   English

在javascript中动态添加输入

[英]dynamic add input in javascript

I'm new at javascript and I need some help making sense of this code and why it's not working. 我是javascript的新手,我需要一些帮助来理解此代码以及为何不起作用。

<html>
<head>
    <title></title>
</head>
<body>

    <form action="" method="POST">
        <input id="in" type="text" name="name">
    </form>
    <button id="add">addone</button>

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script>
        $('#add').click(function() {
          $('#in').append('<br /><input type="text" name="name">');
        });

    </script>

</body>
</html>

I'm trying to append another html input but I have no ideas why it's not working!?. 我正在尝试附加另一个html输入,但是我不知道为什么它不起作用!?。

An input is self-closing, it has no children, and you can't append to it. 输入是自动关闭的,没有子项,您无法追加。

You can however insert something after it 但是,您可以在其后插入一些内容

$('#in').after('<br /><input type="text" name="name">');

 <html> <head> <title></title> </head> <body> <form action="" method="POST"> <input id="in" type="text" name="name"> </form> <button id="add">addone</button> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <script> $('#add').click(function() { $('#in').after('<br /><input type="text" name="name">'); }); </script> </body> </html> 

Note that your duplicating the name, and depending on what you indend to do with it, using name[] could be a good idea ? 请注意,使用name[]复制名称,并根据您的意愿进行更改,可能是一个好主意?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM