【问题标题】:Adding new row on a table tbody by cloning the last row with events attached通过克隆附加事件的最后一行在表 tbody 上添加新行
【发布时间】:2013-03-07 10:51:04
【问题描述】:

我正在尝试使用可能附加事件的输入字段克隆表的最后一行(在本例中,它是 keyup 事件)。我还更改了输入字段的 ID 以反映它们所在的行,例如:

table[0].field1,table[0].field2...table[1].field1...等

问题是我可以添加一行,它也可以获取事件,当我在新的克隆输入上写入时,它们确实会启动事件。但仅在创建的第一行。如果我创建一个新的,它将正确地呈现带有输入的行,而不是事件。方法如下:

addRow= function(tableid){

    //jquery selector get table tbody with id 
    var table=jQuery('table[id="'+tableid+'"] >tbody');


    //get last row containing input fields with tr class hoverTransparente      
    var lastRow=jQuery('table[id="'+tableid+'"] > tbody > tr:last');

    //make a clone of the row
    var clones = lastRow.clone(true); // copy events/children too

    //get the input fields from the cloned row
    var clonedInPuts=clones.find('input');

    //for each input
    jQuery(clonedInPuts).each(function (){

        //set new input val to empty
        jQuery(this).val("");
        var inputId=jQuery(this).attr('id');

        //table id
        var table=inputId.split("[")[0];
        //column id
        var tableField=inputId.split(".")[1];

        var idnumber=inputId.indexOf("[")+1;

        //convert to number to make addition for new id index
        var number = Number(inputId.charAt(idnumber))+1;
        //replace id index with incrementaed value
        var newId=inputId.replace(inputId.charAt(idnumber),number);

        //change id for new one
        jQuery(this).attr('id',newId);

        //check if this variable exists/is not undefined
        if(window["elements_"+table+"_"+tableField]){
            window["elements_"+table+"_"+tableField].push(jQuery(this).get(0));
        }
    });

    clones.appendTo(table);


}

有什么想法吗?当我尝试在 chrome 中调试时,输入元素的 domtree 中的事件 onkeyup 为 null 但是如果我直接选择使用 jquery 并获取 .data('events') 方法,它确实返回一个数组,其中包含附加到输入字段的事件. onkeyup 不应该返回与 null 不同的东西吗?

【问题讨论】:

  • 如何将keyup事件附加到表格行?
  • 什么意思?只有输入字段有 keyup events.jquery .clone() 如果您将参数“withDataAndEvents”设置为 true,则该方法也应该复制事件。

标签: javascript jquery clone


【解决方案1】:

好的,所以问题不在于这一方面,而在于在现有行的原始输入中创建事件的原始方法。你需要这样做:

var selectorStr='input[id^='+table+']&[id$='+tableField+']';
jQuery(document).on('keyup',selectorStr,function(event) {...})

代替:

var elements=jQuery('input[id^='+table+']&[id$='+tableField+']');

elements.each(function() {

jQuery(this).keyup(function(){...})
});

这将解决向平板电脑添加新行和输入事件实际搜索新添加的输入的问题。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多