同位素动态排序 [英] Isotope Dynamic Sorts

查看:87
本文介绍了同位素动态排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery Isotope插件(http://isotope.metafizzy.co/)这很棒,但我在创建排序时遇到问题。它更像是一个JavaScript问题,而不是与Isotope本身有关。

I'm using the jQuery Isotope plugin (http://isotope.metafizzy.co/) which is awesome, but I have a problem with creating the sorts. It's more of a JavaScript problem than anything to do with Isotope itself.

问题是我正在动态构建排序数据。所以我创建了一个生成sortData的函数。下面是一个例子:

The problem is that I'm building the sort data dynamically. So I've created a function that makes the sortData. An example below:

function getSortData(){
    sortData = {};
    var sorts = ['symbol', 'number', 'score', 'name'];
    for (var i in sorts) {
      sortData[sorts[i]] = function($elem) {
        console.log(sorts[i]);
        return parseInt($elem.find('.'+ sorts[i]).text());     
      }
    }
    return sortData;
  }

所以问题是内部的匿名函数总是在整个getSortData之后运行( )函数已运行。导致sorts数组中的最后一项被分配给sort [i]变量。

So the problem is that the anonymous function inside always runs after the entire getSortData() function has run. Resulting in the last item in the sorts array being assigned to the sort[i] variable.

这显示在这个小提琴中: http://jsfiddle.net/xzZR4/
您会看到名称项始终输出到控制台。

This is shown in this fiddle: http://jsfiddle.net/xzZR4/ You'll see that the 'name' item is always outputted to the console.

我想不出另一种方法来创建允许传递正确排序名称的getSortData对象。

I can't think of another way to create the getSortData object that will allow the correct sort name to be passed.

有任何想法的人吗?

推荐答案

得到它......

真正需要的是允许sort字段名称变量在匿名排序函数中具有局部作用域。因为我无法将sort字段直接传递给匿名函数(因为它是由Isotope调用的,所以我无法控制传递给它的参数)。

What was really needed was to allow the sort field name variable to have local scope inside the anonymous sort function. As I wasn't able to pass in the sort field directly into the anonymous function (as it's called by Isotope, so I can't control the parameters passed to it).

所以诀窍就是创建另一个返回匿名函数的函数,这会将该字段作为参数,使其具有局部范围。

So the trick was to create another function that returned an anonymous function, this would take the field as an argument, making it have local scope.

function getSortData(){
    sortData = {};
    var sorts = ['symbol', 'number', 'score', 'name'];
    var sortField;
    for (var i in sorts) {
      sortField = sorts[i];
      sortData[sortField] = getSortDataCallback(sortField)
    }
    return sortData;
  }

function getSortDataCallback(sortField) {
  return function($elem) {
    return parseInt($elem.find('.'+ sortField).text());
  }
}

这篇关于同位素动态排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆