【发布时间】:2021-10-09 00:59:28
【问题描述】:
我的 html 文件中有 3 个 img 标签。我想通过单击存储 9 个图像 src 链接的数组中的按钮来更改所有 3 个 img 的 src。
因此,当页面第一次加载时,它将显示前 3 张图像[0,1,2]。然后在每个 next-btn 单击它会将图像更改为下一个 3 [3,4,5],[6,7,8]。当点击 prev-btn 时,它会返回 3 张图片。
请帮帮我。请建议我有没有其他方法(更好)?
这是我迄今为止尝试过的:
const $img1 = $("#img1")
const $img2 = $("#img2")
const $img3 = $("#img3")
const $nextBtn = $("#next-btn")
const $prevBtn = $("#prev-btn")
$.get("https://someApiLink.com/all.json", function (characters) {
const charactersList = []
for (let i=0; i<characters.length; i++) {
// here casts is another array to match predefined characters with the
// character from the api
if (casts.includes(characters[i].name)) {
charactersList.push(characters[i])
}
}
$img1.attr("src", charactersList[0].image)
$img2.attr("src", charactersList[1].image)
$img3.attr("src", charactersList[2].image)
// it will only switch back and forth 2 images on the first img tag
$nextBtn.on("click", function () {
const src = ($img1.attr("src") === charactersList[0].image)
? charactersList[1].image
: charactersList[0].image;
$img1.attr("src", src)
})
})
【问题讨论】:
标签: javascript html jquery arrays onclick