You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于img.src动态修改startButton.href的条件语句失效

问题修复方案

你的代码存在两个核心问题导致功能失效:

1. 语法错误

  • 每个if/else if语句都未闭合},代码无法正常解析
  • setInterval的回调函数末尾缺少闭合},触发语法报错

2. 逻辑错误

img.src返回的是浏览器解析后的完整绝对URL(例如http://localhost:8080/img/wok.jpg),并非你编写的相对路径./img/wok.jpg,直接用全等比较永远无法匹配成功。


推荐修复代码(最可靠方案)

通过对象数组关联图片路径与跳转链接,直接利用控制切换的index设置内容,避免路径匹配问题:

let index = 1;
let imageLinks = [
    { img: './img/wok.jpg', href: 'recipe.html' },
    { img: './img/croissant.jpg', href: 'recipe-2.html' },
    { img: './img/salad.jpg', href: 'recipe-3.html' }
];

let img = document.getElementById("section-1-img");
let startButton = document.getElementById('startButton');

setInterval(function() {
    img.src = imageLinks[index].img;
    startButton.href = imageLinks[index].href;
    
    index = (index + 1) % imageLinks.length;
}, 2000);

备选修复方案(不修改原数组结构)

如果保留原数组,可通过对应索引的链接数组匹配:

let index = 1;
let images = [
    './img/wok.jpg',
    './img/croissant.jpg',
    './img/salad.jpg'
];
let hrefs = [
    'recipe.html',
    'recipe-2.html',
    'recipe-3.html'
];

let img = document.getElementById("section-1-img");
let startButton = document.getElementById('startButton');

setInterval(function() {
    img.src = images[index];
    startButton.href = hrefs[index];
    
    index = (index + 1) % images.length;
}, 2000);

路径匹配修复方案(坚持用src判断)

若一定要通过图片路径匹配,可获取原始设置的相对路径:

let index = 1;
let images = [
    './img/wok.jpg',
    './img/croissant.jpg',
    './img/salad.jpg'
];

let img = document.getElementById("section-1-img");
let startButton = document.getElementById('startButton');

setInterval(function() {
    img.src = images[index];
    index = (index + 1) % images.length;
    
    const currentSrc = img.getAttribute('src');
    if (currentSrc === './img/wok.jpg') {
        startButton.href = 'recipe.html';
    } else if (currentSrc === './img/croissant.jpg') { 
        startButton.href = 'recipe-2.html';
    } else if (currentSrc === './img/salad.jpg') { 
        startButton.href = 'recipe-3.html';
    }
}, 2000);

内容的提问来源于stack exchange,提问作者Karwan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:13:17