gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:41:04 25 4
gpt4 key购买 nike

基本上,我正在尝试为我正在创建的菜单创建动态航点。我有几个需要创建的航点(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])
)
}

关于javascript - 如何使用 jquery 航点动态生成航点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com