Changing various id's after cloning in jquery

后端 未结 3 778
离开以前
离开以前 2020-12-06 02:14

I\'m trying to clone a table row and update the multiple id\'s to reflect the input fields. I start by doing this and it works:

$(id).clone().attr(\"id\", \"         


        
3条回答
  •  生来不讨喜
    2020-12-06 02:50

    I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.

    function renameCloneIdsAndNames( objClone ) {
    
        if( !objClone.attr( 'data-row-id' ) ) {
            console.error( 'Cloned object must have \'data-row-id\' attribute.' );
        }
    
        if( objClone.attr( 'id' ) ) {
            objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
        }
    
        objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
    
        objClone.find( '[id]' ).each( function() {
    
            var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
    
            $( this ).attr( 'id', strNewId );
    
            if( $( this ).attr( 'name' ) ) {
                var strNewName  = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
                    strName = strName.replace( /[\[\]']+/g, '' );
                    var intNumber = parseInt( strName ) + 1;
                    return '[' + intNumber + ']'
                } );
                $( this ).attr( 'name', strNewName );
            }
        });
    
        return objClone;
    }
    

提交回复
热议问题