选项卡和内容到Array中

时间:2013-05-05 03:02:16

标签: javascript jquery

我有两个标签,例如:

<div id="tabs">
<ul>
<li><a href="#tabs-1">me</a></li>
<li><a href="#tabs-2">you</a></li>
</ul>
<div id="tabs-1">
<ul id="sortable1" class="connectedSortable ui-helper-reset">
  <li class="ui-state-default">Item 1</li>
  <li class="ui-state-default">Item 2</li>
  <li class="ui-state-default">Item 3</li>
  <li class="ui-state-default">Item 4</li>
  <li class="ui-state-default">Item 5</li>
  </ul>
   </div>
   <div id="tabs-2">
  <ul id="sortable2" class="connectedSortable ui-helper-reset">
  <li class="ui-state-highlight">Item 5</li>
  <li class="ui-state-highlight">Item 6</li>
  <li class="ui-state-highlight">Item 7</li>
  <li class="ui-state-highlight">Item 8</li>
  <li class="ui-state-highlight">Item 9</li>
   </ul>
  </div>
  </div>

我想把它全部变成数组:me =&gt; 1,2,3,4,5你=&gt; 5,6,7,8,9任何想法?想到也许sortable1&lt; li.index并给每个li id,但如何将它与tab连接?没什么好帮的。

3 个答案:

答案 0 :(得分:4)

var obj = {};

$('#tabs > ul li a').each(function(i,ele) {
    obj[$(ele).text()] = $.map($('li', $(ele).attr('href')), function(k, i) {
        return $(k).text();
    });
});

FIDDLE

答案 1 :(得分:1)

var meid = $("#tabs a:contains(me)").attr("href");
var youid = $("#tabs a:contains(you)").attr("href");

var me = $("li", $(meid)).map(function() { return $(this).text() });
var you = $("li", $(youid)).map(function() { return $(this).text() });

答案 2 :(得分:0)

这些家伙提供了更简洁的答案。我没有使用$ .map,但这是我写的(可能对某人有用):

var tabs = $("#tabs");
var firstUL = tabs.first("ul");
var akeys = firstUL.find("a");

var valueDivs = tabs.children("div");

var dictionary = {};

$.each(akeys, function(index, value) {
    var key = $(value).text();
    dictionary[key]  = $(valueDivs[index]).find("li");
});

//now dictionary contains all the <li> elements organized by the names in the first ul
//the beauty of JavaScript's dynamic features:
alert($(dictionary.me[0]).text()); //this will show Item 1
alert($(dictionary["you"][4]).text()); //this will show Item 9