如何使用单选按钮和切换大小写用JavaScript更改img



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

我的代码片段:

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或其他,只保留您的普通js(简单地对您的收音机应用onclick。

示例:

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

最新更新