简体   繁体   English

字符串插补不适用于一个以上单词的字符串

[英]String Interpolation not working as expected for a string with more than one word

The code removes all options from a select box and updates them. 该代码从一个选择框中删除所有选项并进行更新。 The issue is that the value for each option is not updating correctly. 问题是每个选项的值未正确更新。

What is happening is the value for each option is updated with just the first word of a string, which is incorrect. 发生的情况是,每个选项的值仅用字符串的第一个单词更新,这是不正确的。 I want the value to be updated with the entire string. 我想用整个字符串更新值。

Code: 码:

service_selection.children().remove();
$.each(data, function(index,value){
    service_selection.append("<option value=" + value.description + ">" + value.description + "</option>");
});

Example: Let's say value.description = "Hello World Foo Bar". 示例:假设value.description =“ Hello World Foo Bar”。

The html shows it only assigns "Hello" to the option's value instead of "Hello World Foo Bar" to the option's value. html显示仅将“ Hello”分配给选项的值,而不是“ Hello World Foo Bar”分配给选项的值。

The current html after being updated looks like this: 更新后的当前html如下所示:

<option value="Hello" World Foo Bar>Hello World Foo Bar</option>

You forgot to add " for the actual html value (it has to be surrounded by "), therfor it will cut after the first white space. 您忘记为实际的html值添加“(必须用“围起来”),否则它将在第一个空格之后被剪切。

The correct code would look like this: 正确的代码如下所示:

    service_selection.children().remove();
$.each(data, function(index,value){
    service_selection.append("<option value='" + value.description + "'>" + value.description + "</option>");
});

(notice the single ' I added after value= and before >) (请注意,我在value =之后和>之前添加了一个'

You have issues with quotes in your current code. 您在当前代码中的引号有问题。

I'd personally do something like: 我个人会做类似的事情:

var opts = "";
$.each(data, function(index, value) {
    opts += '<option value="' + value.description + '">' + value.description + '</option>';
});
service_selection.html(opts);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM