【问题标题】:Jquery removing string but keeping structureJquery删除字符串但保持结构
【发布时间】:2013-01-23 06:40:00
【问题描述】:

我很喜欢 a previous post,它专门讨论了从元素内部删除字符串。这样做的代码是:

  $this.text( $this.text().replace("text to strip out", "") );

我已经成功删除了文本“类别:”

仅供参考:这是一个博客页面,其中包含动态添加的类别。在我去掉“类别:”之前的 HTML 结构:

<container>
   <div class="categories">
     "categories: "  //This is what I strip out with above code
     <a href = "...">Category Name</a> //This is a linked category name
   </div>
</container>

问题是,当我删除“类别:”时,它也会删除并留下未链接的“类别名称”

jquery 运行后 html 是这样的:

 <container>
   <div class="categories">Category Name</div>
</container>

我需要保持链接处于活动状态,因为我希望用户能够点击“类别名称”来保持。

【问题讨论】:

  • 您用于替换的代码是否包含有关链接的任何内容?

标签: jquery replace blogs


【解决方案1】:

一种方法,不知道是否是最好的方法,是将锚元素保存为 javascript 变量。然后,在您删除要删除的内容后,将锚重新注入。

【讨论】:

    【解决方案2】:

    试试这个...

    $("div.categories").each(function() {
        var $this = $(this);
        $this.html($this.html().replace("categories: ", ""));
    });
    

    【讨论】:

      【解决方案3】:

      要删除textNode,您需要使用contents() 来检索它们,然后是filter()remove() 的组合,如下所示:

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

      Example fiddle

      请注意,这将删除所有直接子文本节点。如果要按节点的文本进行过滤,请相应修改filter()函数。

      【讨论】:

        猜你喜欢
        • 2022-08-17
        • 2018-11-24
        • 1970-01-01
        • 2020-01-27
        • 2013-04-07
        • 1970-01-01
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        相关资源
        最近更新 更多