【问题标题】:wrap only text within a selection in jquery在 jquery 的选择中仅包装文本
【发布时间】:2025-12-25 08:10:12
【问题描述】:

我在一个页面上重复了以下标记:

<div class="RebalanceCellBroadACName">
   <img src="someimage.png" />
   Accounts
</div>

我希望使用 jquery 仅将单词“accounts”包装在具有类 .orange-category 的跨度中。 我发现以下内容:

$(".RebalanceCellBroadACName").wrapInner("<span class='orange-category' />");

包装图像和文本。 这在控制台中输入时会返回连接在一起的所有文本实例:

$(".RebalanceCellBroadACName").text();

但是下面返回错误“未定义不是函数”,我认为这是因为我选择的是字符串而不是 jQuery 对象。

$(".RebalanceCellBroadACName").text().wrapAll("<span class='orange-category' />");

因此,对于如何通过 jquery 最好地实现以下结果,我们将不胜感激:

<div class="RebalanceCellBroadACName">
   <img src="someimage.png" />
   <span class='orange-category' />Accounts</span>
</div>

对于页面上的每个 .RebalanceCellBroadACName 实例。提前感谢您的帮助。

【问题讨论】:

  • 不是解决方案,但您没有关闭 img 的 src 属性(" 缺失)

标签: javascript jquery html


【解决方案1】:

解决方案:

$(".RebalanceCellBroadACName").each(function(){
    var img = $('img', this).detach();
    $(this).wrapInner("<span class='orange-category' />").prepend(img);
})

【讨论】:

    【解决方案2】:

    虽然您无权访问文本节点,但您可以访问作为 DOM 元素的子节点。

    所以基本上你可以克隆父级,删除子级,包装文本并最终将其替换为原始文本。

    $(".RebalanceCellBroadACName").each(function(){
        var $this = $(this);
    
        var all_text = $this.html();
        var clean_text = $this.clone()    //clone the element
                           .children() //select all the children
                           .remove()   //remove all the children
                           .end()  //again go back to selected element
                           .text().trim();
        var new_text = "<span class='orange-category'>"+clean_text+"</span>"    
    
        $this.html(all_text.replace(clean_text, new_text));
    })
    

    http://jsfiddle.net/p2he9h2k/

    【讨论】: