Use jQuery to convert table to div's and append th in front of each td

前端 未结 2 1261
醉酒成梦
醉酒成梦 2021-02-10 06:26

I am trying to convert all tables to divs and add the th html or contents of the th in from of each td that is converted to a div.

So my table would look like this:

2条回答
  •  我寻月下人不归
    2021-02-10 07:15

    Here is my improvisation :)

    Add data-name tags to each in order to distinguish the names of the fields:

    Title 1 Title 2 Title 3 Title 4 Title 5
    Data 1 Data 2 Data 3 Data 4 Data 5

    And try the code below. At least you will get exactly the structure you need.

    $("table").replaceWith(function() {
        var block = $("
    ").addClass("box"); $("tr:first th", this).each(function() { var name = $(this).data("name"); var spanLabel = $("").addClass(name + "-label").html(this.innerHTML); var spanData = $("").addClass(name + "-data"); $("
    ").addClass("row-" + name).append(spanLabel, " : ", spanData).appendTo(block); }); $("tr:last td", this).each(function(index) { block.children("div:eq(" + index + ")").children(":last").html(this.innerHTML); }); return block; });

    DEMO: http://jsfiddle.net/BsUVA/


    UPDATE. If you unable to add extra data attributes to tags, there is not a big problem. For not hardcoding, we can move the names to array (as follows) and use it instead.

    var names = [
        "fname",
        "lname",
        "address",
        "city",
        "state"
    ];
    

    DEMO: http://jsfiddle.net/BsUVA/1/

提交回复
热议问题