我正在使用 isotope.js 来显示许多包含不同语言文本的框。(小提琴)项目可以按语言排序 - 单击链接后,具有所选语言的项目将在列表顶部排序,使用 getSortData 和此代码:
var $container = $('#container');
$container.isotope({
itemSelector: '.tipp',
getSortData : {
fr : function( $elem ) {
var isFr = $elem.hasClass('fr');
return (!isFr?' ':'');
},
en : function( $elem ) {
var isEn = $elem.hasClass('en');
return (!isEn?' ':'');
},
de : function( $elem ) {
var isDe = $elem.hasClass('de');
return (!isDe?' ':'');
}
// + 20 more languages!!!
}
});
这很好用,但语言列表会更长(24 种语言)。
我在问是否可以从数组中获取排序数据,或者编写一个函数来获取所有使用的(语言)类作为 sortData。
我找到了一篇关于此类功能的教程的文章,但这段代码对我不起作用:
function createSort(){
var sorts = {};
var $source = jQuery('source'); //from where I will read data
$source.each(function() {
var $element = jQuery(this),
findBy = $element.children('a').data('sort-type'), //element, numerical data, data attribute or a property
key = $element.children('a').data('option-value'); //the name of the element, numerical data, data attribute or a property
//if the sort is based on a css class (an element)
if(findBy === "class"){
sortData[key] = function($elem){return $elem.find('.'+ key).text();};
}
//if the sort is based on a data attribute (in my scenario is a numerical attribute)
if(findBy === "attr"){
sortData[key] = function($elem){return parseInt($elem.attr('data-category-' + key), 10);};
}
});
return sortData;
}
//then I call the function and pass the result to getSortData
var sort_data = createSort(),
$container.isotope({
//more code.
getSortData:sort_data
});
稍后我不想使用链接导航,我将使用 BBQ Hash 历史记录对外部链接中的项目进行排序(即 www.someurl.com/index.htm#sortBy=fr)所以不应该有任何导航或链接列表,我想直接从项目中获取类,或者至少在我的同位素代码之上指定一组语言类 ['fr', 'de', 'en']
基本上这是一个优化问题,因为写下相同的代码段 24 次似乎效率低下,对吧?
再次链接到我至少丰富多彩的jsfiddle。
非常感谢您的帮助!