簡體   English   中英

如何使用jquery航點動態生成航點?

[英]How to dynamically generate waypoints using jquery waypoints?

所以基本上,我正在嘗試為我正在創建的菜單創建動態路標。 我有幾個需要創建的航路點(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,因為它超出了范圍。 有沒有辦法解決問題? 任何和所有的幫助表示贊賞! 謝謝!

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])
    )
}

你可以通過添加相應的“tab”作為屬性來解決這個問題,比如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
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM