jQuery Isotope - getSortData的动态对象

时间:2015-04-23 16:24:09

标签: jquery jquery-isotope

我正在使用[jQuery Isotope] [1]的排序功能更新我的网站。

问题是我的排序链接列表是由Wordpress动态生成的 ...我希望每次添加或删除链接时都避免编辑脚本。

这是一个JSFiddle:http://jsfiddle.net/t66L2qm6/1/

排序链接被声明为Isotope的doc:

推荐
$container.isotope({
  getSortData : {
    design : function( $elem ) {
      var isDesign = $elem.hasClass('design');
      return (!isDesign?' ':'');
    },
    architecture : function( $elem ) {
      var isArchitecture = $elem.hasClass('architecture');
      return (!isArchitecture?' ':'');
    }
  }
)};

所以如果我添加例如a'摄影'链接,我必须修改我的JS代码,我想避免的。

我在这件事上失去了所有的头发......我读了几十篇Google搜索结果,没有成功......我找到了这个Stackoverflow主题:Isotope add dynamically getSortData 但是不了解解决方案也不能让它发挥作用。

我想过做一个函数,它会为找到的每个链接创建一个对象,在getSortData上调用:

function getLinks() {
  $('#main-nav').find('a').each(function() {
    var linkName = $(this).attr('data-option-value');
    // here output:
    linkName : function( $elem ) {
      var islinkName = $elem.hasClass('linkName');
      return (!islinkName?' ':'');
    }
  });
}

$container.isotope({
  getSortData : getLinks();
});

不知道我是否走在正确的轨道上...... 任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:0)

我设法找到了一个解决方案,我在这里发布了解决同样问题的解决方案:

我们在容器DIV上初始化Isotope,而没有定义'getSortData'选项:

var $container = $('#container'), 
isotopeArguments = { 
  itemSelector: '.block',
  filter: '*',
  layoutMode: 'masonry',
  getSortData: { } 
};

然后,我们创建一个数组,我们将每个链接的'data-option-value'放入'#sort-by',这基本上就是nav div:

var arr = [];
$('#sort-by').find('a').each(function() {
  arr.push($(this).attr('data-option-value'));
});

然后,对于数组的每个值,我们将正确的标记写入'isotopeArguments':

$.each(arr, function(index, value) {
    isotopeArguments.getSortData[value] = function (value) {
        return function (element) {
            return element.hasClass(value) ? '' : ' ';
        };
    }(value);
});

最后,我们重新启动了同位素:

$container.isotope(isotopeArguments);

最终代码:

var $container = $('#container'), 
isotopeArguments = { 
  itemSelector: '.block',
  filter: '*',
  layoutMode: 'masonry',
  getSortData: { } 
};

var arr = [];
$('#sort-by').find('a').each(function() {
  arr.push($(this).attr('data-option-value'));
});

$.each(arr, function(index, value) {
    isotopeArguments.getSortData[value] = function (value) {
        return function (element) {
            return element.hasClass(value) ? '' : ' ';
        };
    }(value);
});

$container.isotope(isotopeArguments);