gpt4 book ai didi

javascript - 将 html 更改为数组中的下一项 - jquery

转载 作者:行者123 更新时间:2023-12-02 18:12:50 26 4
gpt4 key购买 nike

我的第一个数组,我以为很简单,但事实并非如此(尽管我对 js 的了解很少)。

我正在尝试在单击事件上(按顺序)迭代数组。因此,在前端,您将看到一个事实,然后您将单击一个按钮来查看下一个事实......简单的想法。

问:当一切正常时,在数组的末尾,当用户单击查看下一个时会发生什么?我该如何处理这个问题?

JS

$(document).ready( function() {
function factsInit() {
// Define all facts
var factText = [
"Oxford won the first Boat Race, which took place on 10th June 1829 at Henley-on-Thames.",
"In 2003, Oxford won the closest ever Boat Race by just one foot.",
"Oxford coxswain Sue Brown became the first woman to participate in The Boat Race in 1981.",
"Oxford's victorious 2009 Blue Boat was the heaviest in the history of the race at an average of 15st 9lb 13oz (99.7kg) per rower.",
"In 2012, Oxford's reserve crew, Isis, beat Goldie by 5 lengths to set the course record for the reserve race at 16:41."
],
factImage = [
"/clients/oubc/assets/img/factimage_firstrace.jpg",
"/clients/oubc/assets/img/factimage_oubc2003.jpg",
"/clients/oubc/assets/img/factimage_oubcsuebrown.jpg",
"/clients/oubc/assets/img/factimage_oubc2009heaviestever.jpg",
"/clients/oubc/assets/img/factimage_isis2012.jpg"
];

// Apply these facts
$('#widget_facts .fact_text').html(factText[0]);
$('#widget_facts .fact_image > *').attr('src', factImage[0]);

// Go to next fact on click
$('#widget_facts .link > a').click( function() {
$('#widget_facts .fact_text').html(factText++);
$('#widget_facts .fact_image > *').attr('src', factImage++);
});
}
// Run the first fact
factsInit();
});

最佳答案

基本上,您想要增加一个计数器变量,并使用它来访问您所拥有的数组的索引。

//declare the counter var
var factCounter = 0;

//setup event handler for click event
$('#widget_facts .link > a').click( function() {

//change the text based on the current counter value
$('#widget_facts .fact_text').html(factText[factCounter]);

//change the image based on the current counter value
$('#widget_facts .fact_image > *').attr('src', factImage[factCounter]);

//increment the counter var for next time
factCounter++;

//if the counter var is too large for the number of indexes we've got to work with
if (factCounter >= factText.length) {

//start over at zero
factCounter = 0;
}
});

如果您从显示第一个索引开始并希望在第一次点击时显示第二个索引,您还可以在更新值之前放置 factCounter 增量代码。

由于数组是零索引的,因此检查计数器是否大于或等于索引数基本上就是检查索引是否存在。如果当前计数器值等于索引数,则计数器值处不存在索引(因为从零而不是一开始)。

关于javascript - 将 html 更改为数组中的下一项 - jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19571071/

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