为什么我的选项标签没有附加在动态生成的选择标签上

时间:2019-08-16 17:00:28

标签: javascript jquery html dom

我有一个动态生成的select标记,然后,我必须进行ajax调用以查询一些值并循环遍历它,并动态生成options标记。但是由于某种原因,我无法在我的选择标签上附加一个option标签。这不是异步问题吗?

const firstElemTd = $('#none td:first-child');

firstElemTd.append(`<select id="the-select"></select>`);

const selectTag = $(`#the-select`);

$.ajax({
      method: 'GET',
      url: url,
      dataType: 'json',
      success: function(response) {
        $.each(response, function(key, balyu) {
          selectTag.append($('<option>', {value: balyu.name}).text(balyu.name));
        });
      }
    });

2 个答案:

答案 0 :(得分:2)

首先将selectTag创建为jQuery对象。然后可以附加到它。

$(function(){
    const $firstElemTd = $('#none td:first-child');
    const $selectTag = $('<select></select>');
    //append the selectTag to the td
    $firstElemTd.append($selectTag);
    //now that the selectTag is a distinct jQuery object you can append to it. EG:
    var response = [{"name":"a"},{"name":"b"},{"name":"c"}];
    $.each(response, function(key, balyu) {
      $selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
    });

/* The same thing in the ajax response should work too.
(commented out here for the snippet)
    $.ajax({
      method: 'GET',
      url: url,
      dataType: 'json',
      success: function(response) {
        $.each(response, function(key, balyu) {
          $selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
        });
      }
    });
   */ 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="none"><tr><td></td></table>

答案 1 :(得分:1)

您错误地构造了$ .each

$.ajax({
  method: 'GET',
  url: url,
  dataType: 'json',
  success: function(response) {
     $.each(response, function(key, balyu) {
        selectTag.append($('<option></option>', 
              {value: balyu.name, 
               text: balyu.name}
        ));
     });
  }
});

您还可以采用另一种方法:

$.ajax({
    method: 'GET',
    url: url,
    dataType: 'json',
    success: function(response) {
        $.each(response, function(key, balyu) {        
            selectTag.append($('<option></option>'
                .val(balyu.name)
                .text(balyu.name));
        });
    }
});

这两种方法都会为您提供所需的内容。