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

如何使用单选按钮和开关盒使用JavaScript更改img?,javascript,checkbox,switch-statement,radio-button,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-toteba

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

我的代码片段:

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">
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或其他,而只剩下香草js)简单地对无线电应用onclick

例如:


您没有设置侦听器或其他设备来查看输入。您只需调用您的函数,该函数将在单击它时调用它当前所处的状态。
 <input type="radio" onclick="changeTotebagColor()" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">