【问题标题】:jQuery / Regex: remove Div with nested Divs from TDjQuery / Regex:从 TD 中删除带有嵌套 Div 的 Div
【发布时间】:2014-04-17 05:17:20
【问题描述】:

我有一个 TD,它始终包含一个 div 和 div 之外的一些文本。

div 有四个嵌套的 div,它们始终遵循以下结构。 我唯一感兴趣的是这个 TD 中出现在主 div 之外的文本,其他所有内容都应该删除。

我要保留的文本各不相同,其余的结构是固定的。

示例 TD:

<td id="myTD">
    <div id="show_status_1622327228" class="nor_addr_status" onmouseout="show_status_div(2, this);" onmouseover="show_status_div(1, this);" style="display: none;">
        <div id="status_safe_1622327228" class="status_hov" onmouseout="javascript:chgcolor(2, this);" onmouseover="javascript:chgcolor(1, this);">
            Text1
        </div>
        <div id="status_unknown_1622327228" class="status_hov" onmouseout="javascript:chgcolor(2, this);" onmouseover="javascript:chgcolor(1, this);">
            Text2
        </div>
        <div id="status_pr_1622327228" class="status_hov" onmouseout="javascript:chgcolor(2, this);" onmouseover="javascript:chgcolor(1, this);" style="background-color: rgb(255, 255, 255);">
            Text3
        </div>
        <div id="status_fraud_1622327228" class="status_hov" onmouseout="javascript:chgcolor(2, this);" onmouseover="javascript:chgcolor(1, this);" style="background-color: rgb(255, 255, 255);">
            Text4
        </div>
    </div>
    The only text I want to keep
</td>

我尝试了以下方法,但这不起作用 - 可能是因为嵌套的 div:

$('#myTD').text().replace(/<div[\s\S]+?<\/div>/g, "").replace(/<a[\s\S]+?<\/a>/g, ""));

我的问题是它保留了嵌套 div 中的文本(Text1、Text2、Text3、Text4)。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    中国刚刚死去十只小猫,四只独角兽被残忍绝育!
    你为什么要用正则表达式做这样的事情?

    要删除每个 DOM 节点,只保留 textNodes,过滤 nodeType 并删除其余的。

    $('#myTD').contents().filter(function() {
        return this.nodeType != 3;
    }).remove();
    

    FIDDLE

    【讨论】:

      【解决方案2】:

      你试过了吗:

      $("#myTD>div").remove()
      

      【讨论】:

      • 非常感谢!
      【解决方案3】:

      就这么简单——

      $('#myTD').find('div').remove();
      

      http://api.jquery.com/remove/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-05
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 1970-01-01
        • 2012-03-22
        • 1970-01-01
        相关资源
        最近更新 更多