如何使用jquery航点动态生成航点?

时间:2015-03-22 23:40:26

标签: javascript jquery

所以基本上,我正在尝试为我正在创建的菜单创建动态路标。我有几个需要创建的航路点(30+)。以下是我到目前为止的情况:

//arrays
var contentArray = new Array(
    "#1790", "#1792", "#1794", "#1720", "#1724", "#1726", "#1728", "#1647", "#1649", "#1651", "#1660", "#1662", "#1664", "#1667",
    "#1669", "#1671", "#1678", "#1680", "#1683", "#1686", "#1688", "#1690", "#1692", "#1694", "#1696", "#1698", "#1700", "#1702",           "#1704", "#1706", "#1708", "#1710", "#1712", "#1714", "#1716", "#1680-1", "#1680-2" 
);

var tabArray = new Array(
    "1739", "1740", "1741", "1742", "1743", "1744", "1745", "1736", "1748", "1749", "1750", "1751", "1752", "1753",
    "1754", "1755", "1757", "1758", "1761", "1763", "1764", "1765", "1766", "1767", "1768", "1769", "1770", "1772",
    "1773", "1774", "1775", "1776", "1779", "1780", "1781", "1759", "1760"
);

for(var i=0; i<contentArray.length; i++){
    $(contentArray[i]).waypoint({
        handler: function (direction) {

        if(direction == "down") {
            $("#menu-item-" + tabArray[i]).addClass("red-bg");
        } else {
            $("#menu-item-" + tabArray[i]).removeClass("red-bg");
        }
    },
    offset: 0
    })
}

数组可能看起来有点时髦,但每个数组的每个索引都应该与其他数组索引相对应。但是,每次运行时,tabArray都会返回undefined,因为它超出了范围。有没有办法解决问题?任何和所有的帮助表示赞赏!谢谢!

2 个答案:

答案 0 :(得分:3)

Blex的答案很好,但它只是一定的范围。问题围绕闭包如何工作以及短暂数据如何丢失。最好/最有用的解决方案是完全创建这样的对象闭包。如下所示:

function createObjectClosure(item){
  return {
    handler: function(direction) {         
        $("#menu-item-" + item).toggleClass("red-bg", direction == "down");
     },
      offset:0
   }
}
for(var i=0; i<contentArray.length; i++){
    $(contentArray[i]).waypoint(createObjectClosure(tabArray[i]));
}

或者(几乎相同的代码......许多人喜欢这种内联函数,但我认为人们更难以遵循):

for (var i = 0; i < contentArray.length; i++) {
    $(contentArray[i]).waypoint(
        function(item) {
            return {
                handler: function(direction) {
                  $("#menu-item-" + item).toggleClass("red-bg", direction == "down");
                },
                offset: 0
            }
        }(tabArray[i])
    )
}

答案 1 :(得分:0)

您可以通过添加相应的“标签”作为属性来解决此问题,例如data-tab

for(var i=0; i<contentArray.length; i++){
    // Add the data-tab to the element and create waypoint
    $(contentArray[i]).attr('data-tab', tabArray[i]).waypoint({
        handler: function (direction) {
            // Grab the data-tab attribute and use it
            var tab = $(this.element).data('tab');
            // You can toggle it without an if statement
            $("#menu-item-" + tab).toggleClass("red-bg", direction == "down");
        },
        offset: 0
    })
}