gpt4 book ai didi

jquery - 使用带有 jquery 函数的数组并循环遍历它

转载 作者:行者123 更新时间:2023-12-01 07:42:50 24 4
gpt4 key购买 nike

我想压缩这段代码:

$("a.clearfix.scalability").click(function() {
$("h2.cases-header").fadeOut(100, function () {
$("h2.cases-header").text("Scalability").fadeIn(100);
})
})
$("a.clearfix.international-compliance").click(function() {
$("h2.cases-header").fadeOut(100, function () {
$('h2.cases-header').text("International Compliance").fadeIn(100);
})
})
$("a.clearfix.rewards").click(function() {
$("h2.cases-header").fadeOut(100, function () {
$('h2.cases-header').text("Rewards Program").fadeIn(100);
})
})
$("a.clearfix.mom-baby").click(function() {
$("h2.cases-header").fadeOut(100, function () {
$('h2.cases-header').text("Mom & Baby").fadeIn(100);
})
})
$("a.clearfix.online-travel-agency").click(function() {
$("h2.cases-header").fadeOut(100, function () {
$('h2.cases-header').text("Online Travel Agency").fadeIn(100);
})
})
$("a.clearfix.food-delivery").click(function() {
$("h2.cases-header").fadeOut(100, function () {
$('h2.cases-header').text("Food Delivery").fadeIn(100);
})
})

我想知道设置此功能的正确方法。我从 2 个单独的数组开始,其中包含我需要插入 jquery 函数的信息,但不确定如何让它循环,或者我是否正确调用数组对象。到目前为止我的代码是:

var anchors = ["a.clearfix.scalability", "a.clearfix.international-
compliance", "International Compliance", "a.clearfix.mom-baby",
"a.clearfix.food-delivery"];
var copy = ["Scalability", "International Compliance", "Rewards Program",
"Online Travel Agency", "Food Delivery"];

$(anchors[0]).click(function() {
$("h2.cases-header").fadeOut(100, function () {
$("h2.cases-header").text(copy[0]).fadeIn(100);
})
})

最佳答案

如果将 JavaScript 数组的形状更改为 JavaScript 对象的单个数组,每个数组都包含一个 anchor 和一个 copy 属性,那么您可以迭代它并根据需要连接事件:

var headers = [
{anchor: "a.clearfix.scalability", copy: "Scalability"},
{anchor: "a.clearfix.international-compliance", copy: "International Compliance"}
];

$.each(headers, function(index, header) {
$(header.anchor).click(function() {
$("h2.cases-header").fadeOut(100, function () {
$("h2.cases-header").text(header.copy).fadeIn(100);
})
})
});

关于jquery - 使用带有 jquery 函数的数组并循环遍历它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685362/

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