附加新行和输入标签

附加新行和输入标签

本文介绍了使用 jQuery 附加新行和输入标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 应用程序,它也设置为使用 Enter 键导航其输入字段.此外,我的表单中有一个控件可以将新行附加到包含我的输入字段的表中.

I have a web application that has set to navigate its input fields using Enter key too. In addition, I have a control in my forms that appends new rows to a table that contains my input fields.

<select name="more" id="more" style="width:50px">
   <option value="0">0</option>
   <option value="5">5</option>
   <option value="10">10</option>
   <option value="20">20</option>
</select>

这就是我用来附加包含输入字段的新行的内容.

And this what I used for appending new rows containing input fields.

$('#more').change(function(e) {
    var current_rows = ($('#myTable tr').length)-1;
    current_rows = parseInt(current_rows);
    var more = $('#more').val();
    more = parseInt(more);
    if (more != '0') {
        for (i = current_rows+1 ; i <= current_rows+more ; i++) {
           // rows HTML tags here as content
           $('#myTable tr:last').after(content);
        }
    }
    $('#more').val('0');
});

想象一下,我第一次有 5 行.每当我按下 Enter 键时,光标都会将其位置从当前字段更改为下一个字段.但是当我添加新行及其输入字段时,第 6 行不会发生任何事情.甚至,使用我之前的代码也无法获取回车的关键代码.

Imagine that I have 5 rows at the first time. Whenever I press Enter, the cursor changes its position from the current field to the next one. But when I append new rows and their input fields, anything will not happen from the 6th row. Even, it can not fetch the key code for the Enter using my previous code.

if (event.keyCode == 13) {
// do something
}

怎么了?

推荐答案

如果您使用的是 jQuery 1.7+,那么请改用 ondelegate.它比旧方法更有效.在这里,我监视表格中表格单元格上的点击事件.当事件发生时,我将 clicked! 添加到表格单元格中.这适用于初始表格单元格和添加的单元格.

If you are in jQuery 1.7+ then use on or delegate instead. It is more efficient than old methods. Here I monitor the table for click events on table cells. When an event occurs I add clicked! to the table cell. This works for both the initial table cells and added ones.

http://jsfiddle.net/WBxQz/1/

$('#more').change(function(e) {
    for (var i = 0; i < $(this).val(); i++) {
        $('#myTable').append('<tr><td></td></tr>');
    }
});

$('table').on('click', 'td', function() {
    $(this).html('clicked!');
});

这篇关于使用 jQuery 附加新行和输入标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:09