如何使用jQuery模板选择选项?

时间:2019-05-29 04:41:03

标签: javascript jquery html css

我正在使用包含select元素的表单。我需要用json格式的数据填充select。如何使用jquery模板填充select元素?

我了解了jquery模板,它是文档。但是仍然无法得到正确的结果。

2问题:对大数据使用jQuery模板是一种好方法,例如:4000列吗?

<div class="col-lg-5">
    <select id="sel"></select>
</div>
<script id="optionTmpl" type="text/x-jquery-tmpl">
            {{each $options}}
                <option value="${$code}">${$title}</option>
            {{/each}}
</script>
    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');

3 个答案:

答案 0 :(得分:1)

您可能会对代码进行如下更改,

preventDefault();
    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');

答案 1 :(得分:1)

如果您的json格式是从服务器端固定的,则可以尝试此操作。

var options = [
{ code: "1", title: "A" },
{ code: "2", title: "B" },
{ code: "3", title: "C" },
{ code: "4", title: "D" },
{ code: "5", title: "E" },
];
$.each(options , function(i, obj){
   $('#select').append($('<option>').text(obj.title).attr('value', obj.code));
});

如果键和值相同,我们还可以将json附加到输入类型选择字段中。

参考:https://jocapc.github.io/jquery-view-engine/

 var options = [ "A" ,"B" ,"C" ,"D"];
          $('#myselect').view(json);

答案 2 :(得分:1)

模板中的变量定义不正确

${$code}应该是${code}

您可以使用以下方法代替plugin

中所述的for循环

$(document).ready(function() {
  var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
  ];

  var markup = '<option value="${code}">${title}</option>';

  // Compile the markup as a named template
  $.template( "optionsTemplate", markup );

  // Render the template with the options data and insert
  // the rendered HTML under the "sel" element
  $.tmpl("optionsTemplate", options ).appendTo("#sel");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<div class="col-lg-5">
    <select id="sel"></select>
</div>