簡體   English   中英

通過克隆附有事件的最后一行,在表正文中添加新行

[英]Adding new row on a table tbody by cloning the last row with events attached

我正在嘗試使用可能附加了事件的輸入字段克隆表的最后一行,(在這種情況下,這是keyup事件)。 我還更改了輸入字段的ID,以反映它們所在的行,例如:

表[0] .field1,表[0] .field2 ...表[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的東西?

好的,問題不在此側,而在於在現有行的原始輸入中創建事件的原始方法。 您需要這樣做:

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(){...})
});

這將解決向平板電腦添加新行的問題,並且輸入事件實際上會搜索新添加的輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM