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

求助:changeHref函数无法执行第二个条件分支的问题

问题分析

你的代码里,select变量是在changeHref函数内部声明的,每次调用函数时都会重新初始化select = 0。这就导致不管你调用多少次函数,永远只会执行第一个if分支,永远碰不到else if (select === 1)的逻辑。

修复方案

方案一:将状态变量移到函数外部

把select变量放在函数外部,让它在函数多次调用之间保留状态:

var select = 0;

function changeHref() {
    const link = document.querySelector("link");

    if (select === 0){
        link.href="css/styleOne.css";
        select = 1;
    } else if (select === 1) {
        link.href="css/styleTwo.css";
        select = 0;
    }
}

方案二:用闭包封装状态(避免全局变量污染)

如果不想使用全局变量,可以用闭包把状态封装起来:

const changeHref = (function() {
    var select = 0;
    return function() {
        const link = document.querySelector("link");
        if (select === 0){
            link.href="css/styleOne.css";
            select = 1;
        } else if (select === 1) {
            link.href="css/styleTwo.css";
            select = 0;
        }
    }
})();

方案三:直接通过当前href判断切换

不需要额外状态变量,直接根据link的当前href值来切换样式:

function changeHref() {
    const link = document.querySelector("link");
    if (link.href.includes("styleOne.css")) {
        link.href = "css/styleTwo.css";
    } else {
        link.href = "css/styleOne.css";
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:52:10