2

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.

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.

This is my JS code:

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

This is the templateArray:

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

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>
4

3 回答 3

2

不要编写原始 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);
}

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

现场测试用例

于 2013-01-13T12:03:12.897 回答
1

Why don't you simply put your value between quotes ?

htmlTemplate.push("<option value=\""+templateArray[i]+"\">"+templateArray[i]+"</option>");

Note that this would still fail with values containing quotes, but there would be less failings.

于 2013-01-13T11:52:30.217 回答
1

You forgot the quotes:

var str = "<option value='"+templateArray[i]+"'>"+templateArray[i]+"</option>";
htmlTemplate.push(str);
于 2013-01-13T11:53:20.053 回答