簡體   English   中英

根據兄弟姐妹包裝元素

[英]Wrap elements depending on their siblings

我試圖將p元素包裝在單個div如果它們在.image類之前或之后。 目前,我只能包裝每個單獨的元素。

這是我的CSS:

<ul>
    <p>this is the first paragraph</p>
    <p>this is the second paragraph</p>
    <div class="image"></div>
    <div class="image"></div>
    <p>this is the third paragraph</p>
    <p>this is the fourth paragraph</p>
</ul>

和我的jQuery:

$('p').wrap('<div class="new" />');
$('.image').wrap('<li />');

這是我的JSFIDDLE: http : //jsfiddle.net/BDqGe/

有人會知道如何根據兄弟姐妹來包裝元素嗎?

您的HTML首先是無效的,因為如果您查看此處

https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/ul

ul的允許內容-零個或多個<li>元素,最終與<ol><ul>元素混合。

但是,您可以使用prevAll()獲取所有先前的兄弟姐妹,並使用.nextAll()獲取元素之后的所有兄弟姐妹,從而包裝所有元素-然后.wrapAll()會將它們全部包裝為一個元素

$('.image') // start at .image
       .prevAll('p') // <-- get all p's before .image
       .wrapAll('<div class="new" />') // wrap all in a div
       .end() // go back to .image
       .nextAll('p') // get all p's after .image
       .wrapAll('<div class="new" />') // wrap all in div
       .end() // go back to .image
       .wrap('<li />'); // wrap .image in li

小提琴

我的方法是

var $ul = $('ul');
$ul.find('.image').wrap('<li />');

$ul.children('p').filter(function(){
    var $prev = $(this).prev();
    return $prev.length == 0 || $(this).prev().is(':not(p)')
}).each(function(){
    $(this).nextUntil(':not(p)').addBack().wrapAll('<li class="new"/>')
})

演示: 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM