javascript - 使用包含空格的变量在 html 中设置 "value"属性

标签 javascript html

我对 HTML/JS 很陌生,所以如果这是一个基本问题,我深表歉意...我尝试在网上查找此问题,但无法找到解决方案。

我正在使用 JS 代码来创建 HTML。我正在尝试使用包含空格的 var 设置“值”属性(带空格的字符串)。当检查 chrome 中的值时,我可以看到字符串设置不正确。

这是我的 JS 代码:

var templateArray = templateString.split("\t");
for (var i = 0; i < templateArray.length; i++) {
  htmlTemplate.push("<option value="+templateArray[i]+">"+templateArray[i]+"</option>");
}

这是模板数组:

templateArray[0] = template_member_information
templateArray[1] = template - member information

这是我在 chrome 中检查时得到的结果:

<option value="template" -="" member="" information="">template - member information</option>
<option value="template_member_information">template_member_information</option>

最佳答案

不要编写原始 HTML,而是仅存储值,然后动态创建 DOM 元素。

假设您拥有名为 values 的数组内的所有值,并具有这样的代码,可以使用具有这些值的项目填充下拉列表:(以及等于该值的文本)

var oDDL = document.getElementById("MyDropDownList");
for (var i = 0; i < values.length; i++) {
    var option = new Option();
    option.value = option.text = values[i];
    oDDL.appendChild(option);
}

这样您就不必搞乱引号,并且代码更加灵活。

Live test case .

关于javascript - 使用包含空格的变量在 html 中设置 "value"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14303138/

相关文章:

javascript - 将 setValues() 与不同长度的数组一起使用

java - 实时获取Facebook用户登录状态

javascript - React.js : How to render separated jsx modules from one app. jsx 文件?

html - 基于用户屏幕分辨率的网页尺寸

css - 旋转木马 Bootstrap 中的拉伸(stretch)图像

javascript - 在 Laravel 5 中通过 URL 传递数据集?

javascript - 如何使用 jquery 将数据传递/阻止到表单中

javascript - Angular 和 Masonry 协同工作

html - 如何从 pdf(jspdf) 中去除黑色背景?

php - Wordpress php while循环按id返回页面