【问题标题】:How to change img with JavaScript using radio button and switch case?如何使用单选按钮和切换大小写使用 JavaScript 更改 img?
【发布时间】:2018-11-22 03:36:54
【问题描述】:

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

我的代码片段:

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,但我现在愿意接受任何解决方案。

【问题讨论】:

  • 您没有设置监听器或其他来观察输入。您只是在调用您的函数,该函数将在您单击它时调用它当前所处的状态。

标签: javascript checkbox switch-statement radio-button


【解决方案1】:

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


您可以通过几种方式解决此问题。最简单的方法是(不更改为 jquery 或其他并单独留下您的 vanilla js)只需将 onclick 应用于您的收音机。

示例:

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

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 2011-06-22
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2022-11-18
    • 2020-06-22
    相关资源
    最近更新 更多