变量中的逗号中断模板文字输出

Comma in variable breaks template literal output

我正在尝试为 <select> 动态设置选项。当为 <outgroup> 设置 label 时,字符串在短语完成之前被断开。例如 HTML 输出:<optgroup label="Computers," electronics,="" &&nbsp;internet="" technology=""></optgroup>

应该是"Computers, Electronics, & Internet technology"

let select = document.querySelector("#category");
const categoriesURL = "INSERT_URL";
  
let str = "";

  fetch(categoriesURL)
    .then(response => response.json())
    .then(data => {
    data.forEach(category => {
      let categoryTitle = category.title;
      str += `<optgroup label=${categoryTitle}></optgroup>`
      category.subcategories.forEach(sub => {
        let subcategories_id = sub.subcategories_id;
        let subcategoriesURL = `INSERT_URL/${subcategories_id}`;
        fetch(subcategoriesURL)
          .then(response => response.json())
          .then(subData => {
          str += `<option value=${sub.subcategories_id}>` + subData.title + "</option>";
        })
      })
    })
    select.innerHTML = "<option disabled selected>Select a category</option>" + str;
  });

此外,我的子类别没有填充...不知道这里出了什么问题。

尝试 label="${categoryTitle}" 加引号,因为没有引号,它会生成

<optgroup label=Computers, Electronics, & Internet technology>

这是无效的,所以浏览器在每个单词周围加上引号,并认为 Electronics 是另一个属性,导致你的问题。