设置“值"html 中带有包含空格的变量的属性 [英] setting a "value" attribute in html with a variable containing spaces
问题描述
我对 HTML/JS 很陌生,所以如果这是一个基本问题,我深表歉意……我试图在网上查找这个问题,但找不到解决方案.
I am very new to HTML/JS so I appologize if this is a basic question... I tried to look this up on the web and was unable to find a solution.
我正在使用 JS 代码创建 HTML.我正在尝试使用包含空格(带空格的字符串)的 var 设置值"属性.检查 chrome 中的值时,我可以看到字符串设置不正确.
I am using a JS code to create an HTML. I am trying to set a "value" attribute with a var containing spaces (string with spaces). when inspecting the value in chrome I can see that the string is not set correctly.
这是我的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 中检查时得到的:
This is what I get when inspecting in chrome:
<option value="template" -="" member="" information="">template - member information</option>
<option value="template_member_information">template_member_information</option>
推荐答案
不要编写原始 HTML,而是只存储值,然后动态创建 DOM 元素.
Don't write raw HTML, instead store only the values, then create the DOM elements on the fly.
假设您在名为 values
的数组中拥有所有值,那么这些代码可以使用具有这些值的项目填充下拉列表:(文本等于该值)
Assuming you have all the values inside array named values
have such code to populate a drop down list with items having those values: (and text equal to the value)
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);
}
这样你就不必乱用引号,代码也更灵活.
This way you don't have to mess around with quotes and the code is more flexible.
这篇关于设置“值"html 中带有包含空格的变量的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!