jQuery追加不使用 

Bob*_*y S 0 jquery json

我有一些json,我试图用来生成一个选择框

例如,json中有一些元素 用于提供一些间距.

[
  {"value":1, "text":"1"}
  {"value":2, "text":" 1. a."}
  {"value":3, "text":"  1. a. i."}
]
Run Code Online (Sandbox Code Playgroud)

然后从我的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());
});
Run Code Online (Sandbox Code Playgroud)

但是,当它显示在HTML中时,它显示的是&nbsp;代替渲染实际空间.

我可以修改jQuery或json数据,无论哪个允许我在需要的地方添加空格,但我不确定如何.

Dan*_*eck 6

你想插入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!)
  }));
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
</select>
Run Code Online (Sandbox Code Playgroud)