How to set table cell value using jquery

后端 未结 5 879
情书的邮戳
情书的邮戳 2021-02-09 18:30

I would like to set the value of all the cells of a table by iterating through them. Ideally I would like to access a Html table like an array i.e. $(\"#tbl\")[row][col]=\

5条回答
  •  一向
    一向 (楼主)
    2021-02-09 19:05

    If you just want to iterate over each cell in the table, either of the following will work:

    $('#tbl td').each(function ()
    {
        var $cell = $(this);
        // do something with the current 
    });
    
    // or,
    
    $('#tbl tr').each(function ()
    {
        var $row = $(this);
        $row.children().each(function ()
        {
            var $cell = $(this);
            // do something with the current  and 
        });
    });
    

    If you want to access the table like an array, you're going to have to build an array yourself:

    var arr = $('#tbl > tbody > tr').map(function ()
    {
        return $(this).children().map(function ()
        {
            return $(this);
        });
    });
    

    However, jQuery doesn't expose an API such that you'll (ever) be able to do simple assignment, as in arr[row][col] = 5;. With the above array, this will work:

    arr[row][col].text(5);
    

    Demo


    Edit

    (1) I dont understand $("#tbl").children().children() why the need for the 2nd children

    Because jQuery's .children() function only returns a set of the element's immediate descendants, not all descendents (e.g. children + grandchildren + ...).

    (2) Why is the 3rd children not a function i.e. children() like the 1st 2.

    Because when you use array notation to access elements of a jQuery collection, you get back the underlying DOM element, not a jQuery object. Use .eq(i) instead of [i]:

    $("#tbl").children().children().eq(row).children().eq(col).append("sdfasdf");
    

    (3) Why is'nt innerHTML not a function i.e. innerHTML()

    As in the answer to your question #2, ...children()[col] returns back a DOM element, not a jQuery object. Most browsers support the DOM element.innerHTML property.

    When using .eq(i) instead of [i], as above, use the .html() jQuery function.

提交回复
热议问题