将多个表转换为节

时间:2015-10-09 22:45:26

标签: jquery css

我正在尝试将基本表格的HTML转换为基本<section>标记。我无法迭代每个表格,以及&#34;内容&#34; div正在重复进入每个部分。看我的小提琴:

$(document).ready(function() {
    var section = $("<section>");
        $("table").each(function(){
            $("td").each(function(){
                var content = $('<div class="content">').html(this.innerHTML);
                section.append(content);
            });
        $("table").replaceWith(section);  
    });
});

http://jsfiddle.net/zre0qof1/

我需要的结果是:

<section>
<div class="content">
<h2>About</h2>
</div>
</section>

<section>
<div class="content">
<h2>Services</h2>
</div>
</section>

我知道它可能非常简单,只需要正确地迭代各个部分/表格,但我似乎无法做到正确。提前谢谢!

1 个答案:

答案 0 :(得分:1)

从你的例子我知道每张桌子都变成了 <section><div class="content"> ALL TABLE CONTENT </div></section> 每张表中只有一个TR和一个TD,所以很难判断你是否还想要别的东西。

如果是这种情况,则此代码可以解决问题:

$(document).ready(function() {
    $("table").each(function(){ // go through every table
        var content = $('<div class="content"></div>'); // create a content div
        $("td", this).each(function(){ // go through every TD in table
            content.append(this.innerHTML); // insert TD content into content div
        });
        $(this).replaceWith($('<section></section>').append(content)); // put content div in section and replace this table with it
    })
});

这是小提琴:http://jsfiddle.net/jtw97u1f/5/

我查了一下,在创建元素时,您应该包含结束标记,因此我将其更改为$('<section></section>')。以下是我用作参考的答案:https://stackoverflow.com/a/6555916/5297207