完成“添加文件”按钮

时间:2017-03-20 22:53:53

标签: javascript jquery html-form

我想在普通编辑器的侧边栏中完成add file按钮。确切地说,

  1. 有一个+按钮。点击它后,会在该处显示输入字段。

  2. 用户输入新文件的名称,然后按键盘上的enter提交

  3. 显示新文件的名称,并在其下方附加一个新的+按钮。

  4. 我编写了以下代码(JSBin)。它不能很好地工作:我不知道为什么键盘上的enter没有提交;因为第三点没有完成。

    有人可以帮我修改代码吗?

    <!DOCTYPE html>
    <html>
    <head>
      <script src="https://code.jquery.com/jquery.min.js"></script>
      <style>
        li { list-style-type: none }
        .add-file { cursor: pointer }
      </style>
    </head>
    <body>
      <ul>
        <li> file 1</li>
        <li> <div class="add-file">+</div>
      </ul>
      <script>
        $('.add-file').click(function (e) {
          e.preventDefault();
          $('.add-file').html('<form action=""><input type="text" name="filename"><input type="submit" style="display:none"></form>');
          $('.add-file').removeClass('add-file');
          $("form").submit(function (event) {
            alert($("input:first").val())
          })
        })
      </script>
    </body>
    </html>
    

1 个答案:

答案 0 :(得分:0)

我个人会把事件监听器放在文本输入上。然后,您可以传递该事件,侦听13的event.which(输入按钮),然后执行您需要对输入值执行的操作。

JSFiddle Here:https://jsfiddle.net/iamjpg/z6c61sbw/

$('.add-file').click(function(e) {
  e.preventDefault();
  $('.add-file').html('<form action=""><input type="text" name="filename"><input type="submit" style="display:none"></form>');
  $('.add-file').removeClass('add-file');

  // Handle the dynamic DOM addition of text input
  $(document).on('keyup', 'input[name="filename"]', function(e) {
    e.stopImmediatePropagation();
    if (e.which === 13) {
      alert(this.value);
      // Now you can submit the form...
    }
  })
})