V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
paloalto
V2EX  ›  前端开发

$('xxxx').html() 把 DOM 节点转成字符串后,如何快速从字符串中剔除某个节点?

  •  
  •   paloalto · 2014-06-19 08:31:57 +08:00 · 5039 次点击
    这是一个创建于 3599 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现在我的做法是先 .clone(),然后 .remove()。

    var $content = $('#content').clone();
    $content.find('.class-1, .class-2, .class-3').remove();
    var content = $content.html();

    最终的 content 就是 剔除后某节点的字符串了。

    但是这么做有点笨,有没有更好的处理办法?
    7 条回复    2014-06-19 10:10:31 +08:00
    lijsh
        1
    lijsh  
       2014-06-19 08:38:28 +08:00 via Android
    写个函数封装下就不笨了,哈哈
    yyfearth
        2
    yyfearth  
       2014-06-19 08:52:46 +08:00
    哪里笨了 不就这样么

    如果你只有字符串 那么也就是 (类似)
    var $content = $(content_html_string);
    content.find('xxx').remove();
    var content = content.html()

    如果你想用regex处理string那就更麻烦而且不靠普了
    yyfearth
        3
    yyfearth  
       2014-06-19 08:53:14 +08:00
    抱歉 第二行应该是 $content.find('.class-1, .class-2, .class-3').remove();
    belin520
        4
    belin520  
       2014-06-19 08:59:06 +08:00
    $(content_html_string).find('class').remove();
    switch
        5
    switch  
       2014-06-19 09:33:49 +08:00
    可以这样:
    $("#content").clone().find(".class-1, .class-2, .class-3").remove().end();
    switch
        6
    switch  
       2014-06-19 09:34:45 +08:00
    $("#content").clone().find(".class-1, .class-2, .class-3").remove().end().html()
    justfindu
        7
    justfindu  
       2014-06-19 10:10:31 +08:00
    你这个方法so 机智 ...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1471 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:36 · PVG 01:36 · LAX 10:36 · JFK 13:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.