简体   繁体   English

为什么新创建的输入标签不会停留在页面上?

[英]Why won't the newly created input tags stay on page?

Im trying to create new input tags based on the number the user enters. 我试图根据用户输入的数字创建新的输入标签。 My code will create the correct amount of tags, but they get removed almost immediately. 我的代码将创建正确数量的标签,但是它们几乎立即被删除。 Why? 为什么?

<form>
 <input type='text' id='input' />
 <button>Submit</button>
</form>
<div id="box">
</div>

<script>
$(document).ready(function() {
 $('button').click(function() {
  var x = $('#input').val(); 
  for(var i=0 ; i < x; i++) {
        $('<input type="text" /><br>').prependTo('#box');
    };
 });
});

</script>

call preventDefault on the event to stop the button action from firing 在事件上调用preventDefault以停止触发button动作

$('button').click(function(e) {
   e.preventDefault();
   var x = $('#input').val(); 
   for(var i=0 ; i < x; i++) {
      $('<input type="text" /><br>').prependTo('#box');
   };
});

FIDDLE 小提琴

Change your existing button to an input with an id and use the id in the JS. 将现有按钮更改为具有ID的输入,然后在JS中使用该ID。 Your problem is the form is being submitted when you click button. 您的问题是单击按钮时正在提交表单。

http://jsfiddle.net/Delorian/65gLvfdx/ http://jsfiddle.net/Delorian/65gLvfdx/

<input type="button" id="update" value="Submit" />

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

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