从 JavaScript 和 CSS 的下拉列表中选择值时,如何在 InnerHTML 中包含空格?

问题描述 投票:0回答:1

如何将空格包含到 InnerHTML 的值中?

所以我从下拉列表中选择一个值,将数组列表作为我的 JS 文件中的常量。

const AppleList = ['iPhone 6s' , 'iPhone 7', 'iPhone 7 Plus','iPhone 8' 
                  ,'iPhone X' , 'iPhone Xs' , 'iPhone Xs Max' ,'iPhone Xr','iPhone 11'
                  ,'iPhone 11 Pro','iPhone 11 Pro Max'
                  ,'iPhone 12','iPhone 12 Pro', 'iPhone 12 Pro Max'
                  ,'iPhone 13','iPhone 13 Pro', 'iPhone 13 Pro Max'
                  ,'iPhone 14','iPhone 14 Pro', 'iPhone 14 Pro Max'];

const GoogleList = ['Pixel 3a' , 'Pixel 4'];
const SamsungList = ['S22','S21'];
const ErrorList = ['Select'];
const Repair1List = ['back' , 'front'];
const Repair2List = ['Pixel 3a Screen', 'Pixel 4 Screen'];
const Repair3List = ['S22 Screen', 'S21 Screen'];
const RepairTypeList =['Glass/LCD Screen Repair', 'Housing / Back Glass ', 
                        ' Front Facing Camera', 'Rear Camera', 'Charge Port' ,'Volume Buttons']


function Brand(e)
{
    listselect.innerHTML="";

  if (Brandselect.value == "Apple")
  {
    AppleList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  } 
  else if(Brandselect.value == "Google")
  {
    GoogleList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  }
   else if(Brandselect.value == "Samsung")
  {
    SamsungList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  }
  else
  {
    ErrorList.forEach(e => listselect.innerHTML += `<option value=${e}">${e}</option>`);
  }
}
Brandselect.addEventListener('change', Brand);
Brand();



function Model(f)
{
    RepairSelect.innerHTML="";
    
  RepairTypeList.forEach(f => RepairSelect.innerHTML += `<option value=${f}">${f}</option>`)


}
listselect.addEventListener('change', Model);
Model();

我张贴了价值观的照片。 例如:“Iphone”6.

我需要它全部是一个字符串,但不确定如何让 innerHTML 做到这一点。

谢谢!

javascript css drop-down-menu html-select innerhtml
1个回答
0
投票

要在

innerHTML
的值中包含空格,您需要将值用引号括在 HTML 标记中。目前,在您的代码中,该值未包含在引号中,当选项值包含空格时会导致问题。

要解决此问题,请修改以下代码行:

AppleList.forEach(e => listselect.innerHTML += `<option value="${e}">${e}</option>`);
GoogleList.forEach(e => listselect.innerHTML += `<option value="${e}">${e}</option>`);
SamsungList.forEach(e => listselect.innerHTML += `<option value="${e}">${e}</option>`);
ErrorList.forEach(e => listselect.innerHTML += `<option value="${e}">${e}</option>`);
RepairTypeList.forEach(f => RepairSelect.innerHTML += `<option value="${f}">${f}</option>`);

通过在

${e}
${f}
周围添加双引号,值中的空格将被保留并正确包含在 HTML 输出中。

© www.soinside.com 2019 - 2024. All rights reserved.