Javascript 根据单选按钮选择更改图像

Javascript 根据单选按钮选择更改图像,javascript,html,Javascript,Html,我有一些js根据选择的单选按钮更改背景图像,但我觉得这是一种“肮脏”的方式。有没有更好的方法来编写此文档以获得更好的功能?甚至可以用纯CSS来做 <input id="main-checkbox-1" type="radio" class="main-container__checkbox" name="main"

我有一些js根据选择的单选按钮更改背景图像,但我觉得这是一种“肮脏”的方式。有没有更好的方法来编写此文档以获得更好的功能?甚至可以用纯CSS来做

<input
            id="main-checkbox-1"
            type="radio"
            class="main-container__checkbox"
            name="main"
            value="first"
            checked
          />
          <label for="main-checkbox-1" class="main-container__checkbox-label"
            >&nbsp;</label
          >
          <input
            id="main-checkbox-2"
            type="radio"
            class="main-container__checkbox"
            name="main"
            value="second"
          />
          <label for="main-checkbox-2" class="main-container__checkbox-label"
            >&nbsp;</label
          >
          <input
            id="main-checkbox-3"
            type="radio"
            class="main-container__checkbox"
            name="main"
            value="third"
          />
          <label for="main-checkbox-3" class="main-container__checkbox-label"
            >&nbsp;</label
          >
您可以使用checkbox元素中的数据-*属性。单击时,仅获取选中的元素并从属性设置url:

var container=document.querySelector(“.main container”);
//设置页面加载
container.style.backgroundImage=“url(../img/main3.jpg)”;
document.querySelectorAll(“.main-container\uuu复选框”).forEach((项)=>{
addEventListener(“单击”,函数(){
//只得到一个选中的
var checked=document.querySelector(“.main-container_uu复选框:选中”);
//获取url
var dataURL=checked.getAttribute('data-url');
//设置url
container.style.backgroundImage=`url(${dataURL})`;
//试验
console.clear();
log(document.querySelector(“.main container”).style.backgroundImage);
});
});


这是否回答了您的问题?一种方法是向提供图像名称的单选按钮添加
dataset
属性。例如,对于带有
value=“first”
的一个,添加
data image=“main3.jpg”
,对于其他的也一样。然后,在forEach()循环中,只需找到选中的项(单选按钮组中只能有一个项)并使用
dataset.image检索图像名称
document.querySelectorAll(".main-container__checkbox").forEach((item) => {
  item.addEventListener("click", function () {
    if (item.checked && item.getAttribute("value") == "first") {
      document.querySelector(".main-container").style.backgroundImage =
        "url(../img/main3.jpg)";
    }
    if (item.checked && item.getAttribute("value") == "second") {
      document.querySelector(".main-container").style.backgroundImage =
        "url(../img/main.jpg)";
    }
    if (item.checked && item.getAttribute("value") == "third") {
      document.querySelector(".main-container").style.backgroundImage =
        "url(../img/main2.jpg)";
    }
  });
});