[英]Surround 2 sibling elements with a span
假設我有這個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)
的目標元素。 我想在一個mouseup上使這個html
<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>
我想恢復原狀。
這與這個問題有關 ,我已經有了“目標元素”。
如果使它更容易,則結構可能總是如上所述。 div
的spans
的集合。 我覺得jQuery nextUntil可能是最好的方法,但是我還不能完全解決。
您可以使用.wrapAll()和.unwrap()在jQuery中包裝元素的集合:
添加亮點:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.