jquery - 仅用 div 替换顶级父表元素,而不用子表替换

标签 jquery html html-table parent replacewith

我正在寻找用 div 替换表格及其行和单元格,但我找到的脚本也用 div 替换每个子表及其后代,这是我不想要的。子表应该保留为表。

如何仅定位顶级父表而不定位任何子表?

    $('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 的样子 [请注意,我在此代码片段中省略了子表中的内容]。可以看到父表中有表。我希望它们保持原样,而不是被替换。

<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>

最佳答案

我能够做到如下所示。

为了使其正常工作,您的子表不能有类calendar-header。如果这样做,您必须将检查 if ($(obj).closest("table").hasClass("calendar-header")) 更改为父表特有的内容。

顺便说一句,请注意,如果您的用户使用 Firefox 和 AdBlockPlus,任何具有 thead 类的 div 都会被 theAd 误认为(“广告” ),并且您的 div 将被插件隐藏(它将动态添加到 elemhide.css 的链接)。因此,我将生成的类名称更改为 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);
}

关于jquery - 仅用 div 替换顶级父表元素,而不用子表替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31151391/

相关文章:

javascript - 在 2D 平面上查找不可访问的点

javascript - Javascript/jQuery 中的缩放图像效果插件

javascript - 通过参数清除缓存

javascript - 如何在 ember.js 中相对于单击操作定位模态

html - 无法将 CSS 应用于表格单元格

javascript - 为什么 JQuery 脚本不删除表行

jquery - 清除焦点并提交字段

javascript - $.ajax({}) 中的 URI 太大

javascript - 在 Safari/iPhone 上更改框架大小

r - 如何在 R 中创建水平表格(markdown)