2011-10-19 5 views
0

我的页面上有四个DIV元素。每个都有自己的数组,我使用data()附加。jquery - 如何选择最长的四个数组中的ID和最后一个元素?

根据用户交互(页面导航),jquery将加载的元素ID存储在其中一个数组中。

的设置,推动要素的作品,看起来像这样:

$('div:jqmData(role="panel")').each(function(index) { 
    if ($(this).jqmData('hash') == 'history') { 
     var id = $(this).jqmData('id'); 
     $(this).data("stack", []); 
     // inital entry = startpage 
     $(this).data("stack").push('#'+$(this).find('.starter').attr('id')); 
     } 
}); 

添加元素:

$('div:jqmData(role="page")').bind("pagechange", function(event) { 
     var $targetPanel = $(event.target),     
     $targetPage = '#'+ $.mobile.path.stripHash(hash); 
     $targetPanel.data("stack").push($targetPage); 
     }); 

我现在需要知道哪些阵列是最长的,什么最后一项是?

不知道该怎么做......

不能使用包括maxValue或数学,因为我只有像#pageSome,#pageOther条目。必须有比循环遍历所有阵列更好的方法,获得它们的长度并尝试如果其他值最高...

感谢您的帮助!

回答

2

您可以使用排序的方法找到最长阵列

var arr = []; 
arr.push([1,2,3,4,5,6]); 
arr.push([1,2,3,4,5,7,8]); 
arr.push([1,2,3,4,5]); 
arr.sort(function(a,b){return b.length - a.length}); 
// arr is now sorted with [0] being the longest array 

随后为了获得这些阵列进行排序,你可以用一个函数让他们像这样:

$('div:jqmData(role="panel"),div:jqmData(role="page")').each(function(index) { 
    arr.push($(this).data("stack")); 
}); 

或者如果数组中的数据不经常更改,那么可以推入数组,因为它们是在问题中指定的两个函数中构建的。

通过评论编辑根据最新的信息

然后,当你想引用最长的数组,并使用它作为一个jQuery选择,你可以使用下面的代码:

var longest = arr[0].join(",") // arr was sorted to have the first index contain the longest array 
$(longest).hide(); 
+0

所以我必须“手动”将所有数组推入arr? – frequent

+0

@frequent不,你可以使用'$('div:jqmData(role =“panel”),div:jqmData(role =“page”)')。each(function(index){arr.push($(this ).data(“stack”))}''或者什么不是。我的例子只是一个技术演示。 –

+0

我想我不是“技术人员”:-D ...谢谢 – frequent

0
var longestArrayStack = function() { 
    var l = Array.prototype.sort.call(arguments, function(a, b) { 
     return b.length - a.length; 
    }); 
    return l[0]; 
}); 

Then:

var arr = []; 
$('div:jqmData(role="page")').each(function(){ 
    arr.push($(this).data("stack")); 
}); 
var longestArr = longestArrayStack(arr); 
相关问题