我曾尝试将包含10个javascript代码块的列表重构为for循环。当他们分开的时候,这是以前的工作,但我似乎看不出我做错了什么。
以前我有10个像下面两个这样的街区。
$("#browse-loan-types-btn").click(function () {
$([document.documentElement, document.body]).animate({
scrollTop: $("#browse-loan-types").offset().top
}, 600);
});
$("#versus-btn").click(function () {
$([document.documentElement, document.body]).animate({
scrollTop: $("#versus").offset().top
}, 600);
});
然后我重构了这个,但是滚动功能不起作用。有人有什么想法吗?
const links = ["browse-loan-types", "versus", "blog-posts", "business-advice", "how-to-get", "types-of-small", "loan-options", "loan requirements", "how-to-apply", "increase-odds"]
$(document).ready(function () {
for (var i = 0; i < links.length; i++) {
$("#" + links[i] + "-btn").click(function () {
$([document.documentElement, document.body]).animate({
scrollTop: $("#" + links[i]).offset().top
}, 600);
});
}
})
单击时,i
已经是最终值。您需要将其封装在IIFE中,以使i
保持为创建点击处理程序时的状态:
const links = ["browse-loan-types", "versus", "blog-posts", "business-advice", "how-to-get", "types-of-small", "loan-options", "loan requirements", "how-to-apply", "increase-odds"]
$(document).ready(function () {
for (var i = 0; i < links.length; i++) {
(function(i) {
$("#" + links[i] + "-btn").click(function () {
$([document.documentElement, document.body]).animate({
scrollTop: $("#" + links[i]).offset().top
}, 600);
});
})(i);
}
})
编辑:或者实际上,我相信你可以更改:
for (var i = 0; i < links.length; i++) {
至
for (let i = 0; i < links.length; i++) {
并获得相同的效果