在文本之前插入空间以动态创建选择选项元素

时间:2015-04-04 11:57:24

标签: jquery html ajax

我需要创建一种&#34; treeview&#34;通过向选项元素文本添加空格看起来像select元素 - <option name='City' />。我的选择以这种方式动态创建:

        $.ajax({
            url: "@Url.Content("~/Home/GetDestinationsTo")",
            data: { 'isRoundTrip': $("input[name='isrt']").is(":checked") ? 2 : 1 },
            type: "post",
            cache: false
        })
            .done(function (result) {
                if (this.Error == null) {
                    optionsto.append($("<option value=''>Куда...</option>"));
                    $.each(result, function () {
                        optionsto.append($("<option name='Country' class='bold info' />").val(this.CountryToId.CountryToId).text(this.CountryToName.CountryToName));
                        optionsto.append($("<option name='City' />").val(this.CityToId.CityToId).text(" " + this.CityToName.CityToName + " (" + this.CityToCode.CityToCode + ")"));
                    });
                } else {
                    $("#errormsg").text(result.Message);
                    $("#modalerror").modal();
                }
            })
            .fail(function (xhr, ajaxOptions, thrownError) {
                $("#errormsg").text(xhr.responseText);
                $("#modalerror").modal();
            });

最后,这必须看起来像<option text=" SomeCityName"/>
我想只有一种方法是添加空间的HTML表示 - &nbsp;,因为只添加空字符串不起作用 - 由浏览器剪切。但它已添加为字符串,而不是HTML,最后看起来像&nbsp;CityName

2 个答案:

答案 0 :(得分:1)

如果您只需要一个级别的缩进,则可以尝试<optgroup>标记,如下所示:

<optgroup label="Group 1">
<option>option 1</option>
<option>option 1</option>
<option>option 1</option>
</optgroup>

<optgroup label="Group 2">
<option>option 1</option>
<option>option 1</option>
<option>option 1</option>
</optgroup>

...

完全不一样,但它可能适合你。

答案 1 :(得分:1)

如果有人需要,这是解决方案:

$('select#optionsto > option.city').each(function () {
     $(this).prepend("&nbsp;&nbsp;&nbsp;");
});
相关问题