javascript jquery在使用回车键输入文本时动态添加带有值的表行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11765815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:16:44  来源:igfitidea点击:

jquery to dynamically add table row with value upon entering text input using enter key

javascriptjquery

提问by Jeebsion

Okay .. this is my first question here. Very new with javascript, so hopefully I'd be treated nicely (crossing fingers) ... I have a html code down here:

好的.. 这是我在这里的第一个问题。javascript 非常新,所以希望我能得到很好的对待(交叉手指)......我在这里有一个 html 代码:

<table width="500" border="1">
  <tr>
    <td>No.</td>
    <td>Name</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
<br />
Enter Name: 
<input type="text" name="name" id="name" />

I'm trying to have whatever value I enter in the input "name" to go directly as a new row in the html table attached with a running number (1,2,3,etc) in the "No." column using the "Enter" key instead of clicking on buttons. At the same time the value in "name" will be cleared and focused as to ready for the next value entrance.

我试图将我在输入“名称”中输入的任何值直接作为 html 表中的新行,并在“编号”中附加一个运行编号(1、2、3 等)。列使用“Enter”键而不是单击按钮。同时“name”中的值将被清除并集中为下一个值入口做准备。

回答by j08691

I'll throw you a bone here since this is pretty simple code (and you're new). Try this jsFiddle example.

因为这是非常简单的代码(而且你是新手),所以我会在这里给你一个骨头。试试这个jsFiddle 示例

HTML

HTML

<table width="500" border="1">
  <tr>
    <td>No.</td>
    <td>Name</td>
  </tr>
</table>
<br />
Enter Name: 
<input type="text" name="name" id="name" />?

jQuery

jQuery

var index = 1;
$('input[name=name]').on('keyup', function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
        $('table').append('<tr><td></td><td></td></tr>');
        $('table tr:last td:first').html(index);
        $('table tr:last td:last').html($(this).val());
        $(this).focus().select();
        index++;
    }
});?

回答by Kosmonaut

Jeebison,

吉比森,

Being new to javascript I'm going to phrase this more as a tutorial than the exact answer.

作为 javascript 的新手,我将把它作为教程而不是确切的答案来表述。

First things first- What are the steps that need to occur to make this happen?

第一件事 - 需要采取哪些步骤才能实现这一目标?

  1. get the value of the input
  2. detect the "enter" key press
  3. insert a new row
  4. set the row to the value of the input
  1. 获取输入值
  2. 检测“回车”键按下
  3. 插入新行
  4. 将行设置为输入的值

Ok, now we've dissected each the problem into lots of small tasks. This makes it much easier to look for answers on each of the subsections of the problem?

好的,现在我们已经将每个问题分解为许多小任务。这使得在问题的每个小节上寻找答案变得更加容易?

Next- Do you know about javascript frameworks?

下一个 - 你了解 javascript 框架吗?

When writing javascript many browsers handle parts of the standard differently or certain parts aren't supported at all. As a result, writing javascript entirely by hand is not only cumbersome, but difficult to write cross-browser. Frameworks make development a lot easier and cleaner because they are built to handle the same functions across all browsers.

在编写 javascript 时,许多浏览器以不同的方式处理标准的某些部分,或者根本不支持某些部分。因此,完全手工编写javascript不仅麻烦,而且跨浏览器编写也很困难。框架使开发变得更容易和更清晰,因为它们被构建为在所有浏览器中处理相同的功能。

http://jquery.com-is my favorite and very easy to use so I will give you examples using that.

http://jquery.com- 是我最喜欢的,而且非常容易使用,所以我会给你使用它的例子。

Ok, onto the coding.

好的,进入编码。

First thing, we need to link the framework to the html page. If it's a small site or you're playing around I like to have google host the jQuery for me. Normally you might just download it.

首先,我们需要将框架链接到 html 页面。如果它是一个小网站或者你正在玩,我喜欢让谷歌为我托管 jQuery。通常你可能只是下载它。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

To actually add code and make use of jQuery we need to add some script tags and wait for the DOM (Document Object Model)to be ready on the page.

要实际添加代码并使用 jQuery,我们需要添加一些脚本标签并等待 DOM(文档对象模型)在页面上准备就绪。

<script type="text/javascript">
$(document).ready(function() {
   // do stuff when DOM is ready
});
</script>

Now we need to select the element that we're trying to get data from. jQuery selectors are perfect for this. A simple example is grabbing an element by its "id" attribute.

现在我们需要选择我们试图从中获取数据的元素。jQuery 选择器非常适合这个。一个简单的例子是通过“id”属性抓取一个元素。

In the case of the input we'll use "name". When referencing an ID in a selector, we always precede it with a #.

在输入的情况下,我们将使用“名称”。在选择器中引用 ID 时,我们总是在它前面加上 #。

$('#name').val() 

This will give us the value of the input. Now add another row.

这将为我们提供输入的值。现在添加另一行。

Your table doesn't have an ID, but lets give it one.

您的表没有 ID,但让我们给它一个。

<table id='numbers'>

add the html for the row

为该行添加 html

$('#numbers').append('<tr><td></td><td></td></tr>');

select the first column of the row we just added and add the number.

选择我们刚刚添加的行的第一列并添加数字。

var rows = $('#numbers tr').length;
$('#numbers tr:last td:first').html(rows);

copy the value of the input to the second column

将输入的值复制到第二列

$('#numbers tr:last td:last').html($('#name').val());

remove empty the input

删除空输入

$('#name').val('');

Now to detect the keystroke we will attach a listener to the input and place all of this code inside.

现在为了检测击键,我们将一个监听器附加到输入并将所有这些代码放在里面。

$('#name').on('keyup', function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
        $('#numbers').append('<tr><td></td><td></td></tr>');
        var rowcount = $('#numbers tr').length;
        $('#numbers tr:last td:first').html(rowcount);
        $('#numbers tr:last td:last').html($('#name').val());
        $('#name').val('').focus();
    }
});

This looks good, except $('name') is making extra selections slowing down your code and its redundant inside of a function attached to that object. We can use $(this) instead of $('#name') inside of the listener which references the initial selection done by

这看起来不错,除了 $('name') 进行额外的选择会减慢您的代码及其在附加到该对象的函数内部的冗余。我们可以在侦听器中使用 $(this) 而不是 $('#name') ,它引用了由

$('#name').on('keyup', function(e) {

So we have -

所以我们有——

<script type="text/javascript">
$(document).ready(function() {
   $('#name').on('keyup', function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
        $('#numbers').append('<tr><td></td><td></td></tr>');
        var rowcount = $('#numbers tr').length;
        $('#numbers tr:last td:first').html(rowcount);
        $('#numbers tr:last td:last').html($(this).val());
        $(this).val('').focus();
    }
   });
});
</script>

回答by anAgent

Welcome to Stackoverflow.

欢迎使用 Stackoverflow。

If you're using jQuery, check out jQuery's APIfor detailed information about what functions are available. Your specific question seems to be around events - which you can learn more about here.

如果您使用 jQuery,请查看jQuery 的 API以获取有关可用函数的详细信息。您的具体问题似乎与事件有关 - 您可以在此处了解更多信息。

In short, you'll want to bind an event that delegates the result to another control. I suggest looking at the keyupfunction.

简而言之,您需要绑定一个将结果委托给另一个控件的事件。我建议查看keyup功能。

I hope that helps.

我希望这有帮助。

References:

参考: