2017-08-08 38 views
-1

工作,我有一些JSON,我试图用它来生成一个选择框jQuery的追加不 

的JSON中有一些元素使用 提供一定的间距,例如。

[ 
    {"value":1, "text":"1"} 
    {"value":2, "text":" 1. a."} 
    {"value":3, "text":"  1. a. i."} 
] 

然后从我的jQuery,我得到这些值,并使用.append()替换选项。

$.each(response, function(id, ob) { 
    // Add json results 
    options.append($('<option>', { 
    value: ob.value, 
    text: ob.text 
    })); 

    // Apply 
    $('#select_list').html(options.html()); 
}); 

然而,当它在HTML显示出来,它显示了&nbsp;而不是呈现的实际空间。

我可以修改jQuery或json数据,无论哪个人允许我在需要时添加空格,但我不知道如何。

+2

您插入使用文本方式的HTML。文本形式的' '呈现为' '。但请注意,通过使用.html,它将插入返回的内容。只有在您信任从中获取该数据的服务器时,才能执行此操作,或者正确清理该数据。 –

回答

4

你想插入HTML,而不是文本:

$('select').append($('<option>', { 
 
    value: "foo", 
 
    text: "&nbsp;&nbsp;&nbsp;text" // literal text 
 
    })); 
 

 

 
    $('select').append($('<option>', { 
 
    value: "bar", 
 
    html: "&nbsp;&nbsp;&nbsp;html" // parsed html. (Sanitize it!) 
 
    }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select> 
 
</select>

+0

完美的谢谢。愚蠢的错误。 –

+0

完全没有,我比那个时候更容易被那个人抓到 –

0

试试这个

{"value":3, "text":encodeURIComponent("&nbsp;&nbsp;1. a. i.")} 
0

除了&nbsp;是一个HTML表示 - 所以你需要一个.html()代替的.text()(如已经提到的),这里有一些其他的方式来实现追加

var response = [ 
 
    {"value":1, "text":"1"}, 
 
    {"value":2, "text":"&nbsp;1. a."}, 
 
    {"value":3, "text":"&nbsp;&nbsp;1. a. i."} 
 
]; 
 

 
$.each(response, function(id, ob) { 
 
    $('<option/>', { 
 
    value: ob.value, 
 
    html: ob.text, 
 
    appendTo: '#select_list' 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="select_list"></select>

var response = [ 
 
    {"value":1, "text":"1"}, 
 
    {"value":2, "text":"&nbsp;1. a."}, 
 
    {"value":3, "text":"&nbsp;&nbsp;1. a. i."} 
 
]; 
 

 

 
$("#select_list").append(
 
    response.map(function(o) { 
 
    return `<option value='${o.value}'>${o.text}</option>`; 
 
    }) 
 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="select_list"></select>