用跨度环绕2个同级元素 [英] Surround 2 sibling elements with a span

查看:65
本文介绍了用跨度环绕2个同级元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个HTML

Suppose I have this HTML

<div class="parent">
    <span class="foo">Some text</span>
    <span class="foo">FROM HERE</span>
    <span class="foo">some text</span>
    <span class="foo">TO HERE</span>
    <span class="foo">some text</span>
</div>

现在,我已经将目标元素作为$(start)$(end).我想把这个html放在mouseup上

Now I'll already have the target elements as $(start) and $(end). I want to make this html on a say a mouseup

<div class="parent">
    <span class="foo">Some text</span>
    <span class="highlight">
        <span class="foo">FROM HERE</span>
        <span class="foo">some text</span>
        <span class="foo">TO HERE</span>
    </span>
    <span class="foo">some text</span>
</div>

,我想恢复原状.

这与此问题我已经有了目标元素".

This is related to this question where I already have the 'target elements'.

如果它更容易实现,则结构可能总是如上所述. divspans的集合.我觉得jQuery nextUntil 可能是最好的方法,但我不能完全解决./p>

If it makes it easier, the structure will likely be always as above. A collection of spans within a div. I feel that jQuery nextUntil may be the best approach but I can't quite work it out.

推荐答案

您可以使用 .unwrap():

小提琴演示

添加重点:

var $wrapped = highlight($start, $end, '.foo'); // highlight and get the highlighted items collection

删除突出显示:

$wrapped.unwrap(); // use unwrap on the collection to remove highlight

突出显示功能:

function highlight($start, $end) {
    /** return the wrapped collection **/
    return $start
        .nextUntil($end) // get elements between $start and $end
        .addBack() // add $start back
        .add($end) // add $end
        .wrapAll("<span class='highlight' />"); // wrap them with highlight
}

这篇关于用跨度环绕2个同级元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆