javascript - 如何使用单选按钮和开关盒通过 JavaScript 更改 img?

标签 javascript checkbox switch-statement radio-button

我想使用开关盒根据选中的单选按钮获得背景图像。但是,我没有找到正确的解决方案来从选中的单选按钮获取值。

我的代码片段:

HTML:

<section class="configurator__product">
       ...
</section>

<label for="blue" class="hidden">Blue</label>
<input type="radio" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">
<label for="green" class="hidden">Green</label>
<input type="radio" id="green" name="color-totebag" value="tote-green" class="circle tote-green">
<label for="black" class="hidden">Black</label>
<input type="radio" id="black" name="color-totebag" value="tote-black" class="circle tote-black">

有更多的输入,总共 5 个,因此我不认为使用 if/else 是可选的。但我希望我在这里给出的代码量能够让大家清楚地了解这一点。

JavaScript:

const changeTotebagColor = () => {
    let totebagColor = document.getElementsByName(`color-totebag`).value;
    const $totebagImg = document.querySelector(`.configurator__product`);

    switch (totebagColor) {
        case `tote-blue`:
            $totebagImg.style.backgroundImage = "url('assets/img/totebag_blue')";
        case `tote-green`:
            $totebagImg.style.backgroundImage = "url('assets/img/totebag_green')";
        case `tote-black`:
            $totebagImg.style.backgroundImage = "url('assets/img/totebag_black')";
    }
}

changeTotebagColor();

我希望我想弄清楚的事情有点清楚。我是 JavaScript 新手,所以也许我做错了。我在网上尝试了很多解决方案,但我没有运气。如果可能的话,我还想避免使用内联 JavaScript,但目前我愿意接受任何解决方案。

最佳答案

正如我在评论中提到的,当您单击事物时,事物的设置方式实际上并没有触发您的函数。您可以在函数之后调用它,但这不会“监视”事物。


您可以通过多种方式解决此问题。最简单的方法是(不更改为 jquery 或其他,并保留你的 vanilla js)简单地将 onclick 应用于你的 radio 。

示例:

 <input type="radio" onclick="changeTotebagColor()" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">

关于javascript - 如何使用单选按钮和开关盒通过 JavaScript 更改 img?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53419132/

相关文章:

javascript - 如果选中复选框 > 1,则应用表达式

javascript - 引导电子邮件输入中的 wordpress jetpack 不需要的边框

javascript - $watch JSON 中的对象 Angularjs

html - 如何使整个自定义复选框/Div 可点击——而不仅仅是标签 + 输入

c++ - 如何在 C++ 中使用 switch case 比较字符串

Java Switch 语句 - "or"/"and"可能吗?

java - 具有多个用例的onOff开关的SharedPreferences

javascript - 有没有一种方法可以提供类似于 Rust 枚举的多态类型区分?

javascript - 使用 WebRTC 时不立即显示视频

jquery - 通过选中复选框调用函数 JQuery