2015-09-14 54 views
1

假设我有这样的HTML环绕2,跨度同级元素

<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

<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 question有关,我已经有了'目标元素'。

如果它更容易,结构可能会永远如上。 div内的spans的集合。我觉得jQuery nextUntil可能是最好的方法,但我无法完成它。

回答

1

您可以通过使用.wrapAll().unwrap()包裹在jQuery中,元素的集合:

Fiddle Demo

添加亮点:

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

删除亮点:

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

亮点func:

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 
}