仅用 div 替换 top-level parent table 元素,而不是 child tables

Replace only top-level parent table elements with divs, not child tables

我想用 div 替换 table 及其行和单元格,但我发现的脚本也用 div 替换了每个 child table 及其后代,这我不想。 Child tables 应该保持 tables.

如何只定位 top-level parent table 而不是 children table 中的任何一个?

    $('table.calendar-header').each(function (){
        $(this).replaceWith( $(this).html()
            .replace(/<tbody/gi, "<div class='table'")
            .replace(/<tr/gi, "<div class='tr'")
            .replace(/<\/tr>/gi, "</div>")
            .replace(/<td/gi, "<div class='td")
            .replace(/<\/td>/gi, "</div>")
            .replace(/<\/tbody/gi, "<\/div")
        );
    });

我试过将 :first-child 和 .first() 插入脚本的不同位置,但都无济于事。

这是脚本运行前 HTML 的样子 [请注意,我在该代码片段中遗漏了 child table 的内容]。可以看到parenttable里面有table。我希望它们保持原样,而不是被替换。

<table class="calendar-header" cellspacing="0" cellpadding="6" border="0" style="">
    <tbody>
        <tr>
            <td valign="top">
                <table class="calendar" cellspacing="0" cellpadding="2"></table>
            </td>
            <td align="center">
                <div class="eventNav"></div>
            </td>
            <td valign="top" align="right">
                <table class="calendar" cellspacing="0" cellpadding="2"></table>
            </td>
        </tr>
    </tbody>
</table>

我能够做到如下所示。

为了使其正常工作,您的 child table 不能有 class calendar-header。如果他们这样做,您必须将支票 if ($(obj).closest("table").hasClass("calendar-header")) 更改为您的 parent table.

独有的内容

作为旁注,请注意,如果您的用户使用的是 Firefox 和 AdBlockPlus,任何 div 和 class thead 都会被 theAd 误认为( "the advertisement"),你的 div 将被插件隐藏(它会动态添加一个 link 到 elemhide.css)。所以我将生成的 classes 名称更改为 divTabledivThead 等:

$('table.calendar-header').each(function (){
    // It's important to go from farthest tag to the nearest.
    $(this).find("th").each(replacer);
    $(this).find("td").each(replacer);
    $(this).find("tr").each(replacer);
    $(this).find("tbody").each(replacer);
    $(this).find("thead").each(replacer);
    replacer(0, this); // replace the table tag
});

function replacer(idx, obj) {
    tagName = capitalizeFirstLetter($(obj).prop("tagName").toLowerCase());
    if ($(obj).closest("table").hasClass("calendar-header")) {
        $(obj).replaceWith("<div class='div" + tagName + "'>" + obj.innerHTML + '</div>');
    }
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

每个table都有一个td,对吧?

var cur = $('td').closest('table');
while (cur.closest('table').length > 1)
{
    cur = cur.closest('table');
}

我认为您需要手动提取每个标签,并在 JQuery 中重建 DOM。使用 replace 方法只会盲目地替换所有请求的字符串。