jQuery changing the id attribute of all the children

前端 未结 3 1704
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 05:54

I need some help figuring out how to write some jQuery code.

I need to clone a table dynamically onclick. but then I need to change the ids of the table and its chil

相关标签:
3条回答
  • 2021-01-18 06:33

    you can do

    $Element.children().each(function () {
            this.id = new_id;
     });
    
    0 讨论(0)
  • 2021-01-18 06:41
    $("#table1").find(*)
    

    should be

    table.find("*")
    

    $("#table1") will not return anything on that line of code as you have not yet added the table to the DOM. And * is a selector which should be a string.

    0 讨论(0)
  • 2021-01-18 06:54

    If elem is the parent of your cloned structure and cntr is the counter you said you were maintaining, you can fix all ids in that cloned structure like this:

    function fixIds(elem, cntr) {
        $(elem).find("[id]").add(elem).each(function() {
            this.id = this.id + cntr;
        })
    }
    

    If the ids might already have a cloned number at the end and you want to replace that number, you can do so like this:

    function fixIds(elem, cntr) {
        $(elem).find("[id]").add(elem).each(function() {
            this.id = this.id.replace(/\d+$/, "") + cntr;
        })
    }
    

    So, based on the code you've now added to your question, you could do this:

    <script> 
        var cloneCntr = 1;
        $("button").click(function () { 
            var table = $("#table").clone(true,true) 
            fixIds(table, cloneCntr);
            table.insertAfter("#table") 
            cloneCntr++;
        });
    </script>
    

    Working example: http://jsfiddle.net/jfriend00/wFu9K/

    Note: I also changed the DOM insertion code to insertAfter(), because you can't append one table to another the way you were doing (a table would either go after the existing table or inside a cell in the previous table).


    If you are just trying to add a row, then you need to clone the row, not the whole table.

    You could add a cloned row to the existing table with this code:

    function fixIds(elem, cntr) {
        $(elem).find("[id]").add(elem).each(function() {
            this.id = this.id.replace(/\d+$/, "") + cntr;
        })
    }
    var cloneCntr = 1;
    $("button").click(function () { 
        var row = $("#table tr").first().clone(true,true);
        fixIds(row, cloneCntr++);
        row.appendTo("#table") 
    }); ​
    
    0 讨论(0)
提交回复
热议问题