简体   繁体   English

如何使用.keyup()添加新的输入字段?

[英]how to add new input field with .keyup()?

I have created add button to create input field let me show you my code here 我创建了添加按钮来创建输入字段让我在这里向您展示我的代码

$(document).ready(function(){
    var scntDiv = $('#add_words');
    var wordscount = 1 ;
    var i = $('.line').size() + 1; 
    $('#add').click(function() { 
      wordscount++;
      $('<div class="line">Word is ' + wordscount + '<input type="text" class="input' + wordscount + '" value="' + wordscount + '" /></div>').appendTo(scntDiv); 
      i++; 
      return false;
    });

<a id="add">Add</a>
<div id="add_words">
    <div class="line">Word is 1<input type="text" value="1" /></div>
</div>

I would like to use .keyup() function instead of <a id="add">Add</a> . 我想使用.keyup()函数而不是<a id="add">Add</a> Any one help me please thanks in advance 任何人请帮助我,请提前感谢

Have you tried keyup yet? 你有没有尝试过keyup? It's as simple as assigning the keyup event to the input field instead of using the click event on the div. 它就像将keyup事件分配给输入字段而不是使用div上的click事件一样简单。

The problem I see you'll run into is for every character, on keyup, a new input field will be created, so you'll be able to solve that with one of two ways: 1) Remove the keyup event once a new input field has been created, in which case, from what little information you gave, I'm assuming you would want to assign the keyup event to the new input field so if somebody starts typing in there, another input field is created. 我看到你遇到的问题是对于每个角色,在keyup上,将创建一个新的输入字段,因此你将能够通过以下两种方式之一解决这个问题:1)一旦新的输入,删除keyup事件字段已经创建,在这种情况下,从你给出的少量信息,我假设你想要将keyup事件分配给新的输入字段,所以如果有人开始在那里输入,则创建另一个输入字段。

(You'll need jquery's bind and unbind methods) (你需要jquery的bindunbind方法)

Or 2) create a flag that says if there's a new field or not. 或者2)创建一个标志,说明是否有新字段。 This option is a bit less optimized and the problem that I have with going this route is the event fires for every character that's added to the input field, but I'm just throwing it out there in case you need it, since there's not much detail on what you're trying to accomplish. 这个选项稍微不那么优化了,我走这条路的问题就是每个添加到输入字段的字符的事件都会触发,但我只是把它扔到那里以防你需要它,因为没有多少关于你想要完成什么的细节。

something like this below, here is a list of key codes 下面是这样的, 这里是一个关键代码列表

$(document).keyup(function(e) {
    var key = (e.keyCode ? e.keyCode : e.which);
    if (key === 32) {
        $('body').append('<p>stop touching your keyboard</p>');
    }
});

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

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