开发者

Select from "value" to "value"

开发者 https://www.devze.com 2023-01-03 23:43 出处:网络
I have this <div class=\"item\">1</div> <div class=\"item\">2</div> <div class=\"item\">3</div>

I have this

<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class=开发者_如何学运维"item">8</div>

and I want select from item 1 to item 5 and wrap them into an UL, and select 6 to 8 and wrapp them in another one.

<ul>
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
</ul>


<ul>
      <div class="item">6</div>
      <div class="item">7</div>
      <div class="item">8</div>
</ul>

How can I do that?. Thank you very much


<div> is not a valid child element for <ul>. You should nest <li> elements. As for the selectors, you can use :gt() and :lt():

$('div.item:lt(5)').wrapAll("<div>");
$('div.item:gt(4)').wrapAll("<div>");


To create valid HTML here you need to wrap them as list items as well, getting this result:

<ul>
  <li><div class="item">1</div></li>
  <li><div class="item">2</div></li>
  <li><div class="item">3</div></li>
  <li><div class="item">4</div></li>
  <li><div class="item">5</div></li>
</ul>
<ul>
  <li><div class="item">6</div></li>
  <li><div class="item">7</div></li>
  <li><div class="item">8</div></li>
</ul>

Here's jQuery that will do that wrapping/grouping every 5 elements, and the remaining at the end, it'll work for any number of divs you have:

var elems = $("div.item");
for(var i = 0; i < elems.length; i+=5) {
  elems.slice(i, i+5).wrap('<li></li>').parent().wrapAll("<ul></ul>");
}​

You can see a working demo here, this .wrap()s each element in a <li> then wraps the groups using .wrapAll() in <ul>.


Something like this will get you there...

$('div.item').slice(0, 5).wrapAll('<ul />');
$('div.item').slice(5).wrapAll('<ul />');


Now, this is far from perfect, but for a start:

function findByText(n){
  return $('.item').filter(function(){return $(this).text() == n});
}

$(function(){
   var from = findByText(2);
   var to = findByText(5);
   $('.item').slice(from.index(), to.index() + 1).wrapAll('<div />');
});

It can be improved in many ways - you may want to convert findByText to a plugin that filters a collection, and you defiantly want to check from and to, and probably call $('.item') only once.
I think it's enough to get you going though.

Working example: http://jsbin.com/ehite4/

0

精彩评论

暂无评论...
验证码 换一张
取 消