简体   繁体   English

html onchange事件未从ajax生成的下拉列表中调用

[英]html onchange event not being called from ajax generated dropdown list

I have an ajax generated dropdown list. 我有一个ajax生成的下拉列表。 When the list generates it sends it back to the HTML like below. 列表生成后,将其发送回如下所示的HTML。 However, the HTML side onchange() event does not seem to kick in. How can I get this to work? 但是,HTML端的onchange()事件似乎没有开始。如何使它起作用?

function listSess(){
 var name = document.getElementById("studentID").value;

 $.ajax({
    url : "<%=context%>/ListSessionsServlet?name=" + name,
    type : "POST",
    async : false,
    dataType: "json",
      success : function(data) {
          var toAppend = '';
          $.each(data,function(i,o){

              toAppend += '<option>'+o.sessid+'</option>';
             });

        $('#sessid')
            .find('option')
            .remove()
            .end()
            .append(toAppend);

      }  
});
} 


<select id="sessid" name="sessid" onchange="listStudents();">  <--onchange not working when getting ajax generated list
</select>

If you bind the change event using jQuery instead of inline as a tag attribute, you can trigger it with jQuery in your AJAX callback: 如果您使用jQuery而不是inline作为标记属性绑定更改事件,则可以在AJAX回调中使用jQuery触发它:

// Hook up the change event on DOM ready
$(function() {
    $('#sessid').change(function() {
        listStudents();
    });
});

function listSess(){
 var name = document.getElementById("studentID").value;

 $.ajax({
    url : "<%=context%>/ListSessionsServlet?name=" + name,
    type : "POST",
    async : false,
    dataType: "json",
      success : function(data) {
          var toAppend = '';
          $.each(data,function(i,o){
              toAppend += '<option>'+o.sessid+'</option>';
             });

        $('#sessid')
            .find('option')
            .remove()
            .end()
            .append(toAppend);

        $('#sessid').change(); // fire change
      }  
});
} 

<select id="sessid" name="sessid"></select>

Your current logic for building out the new <options> might not work without them having a value attribute. 您当前构建出新的逻辑<options>可能没有他们有工作的value属性。 Here's how I might change it: 这是我可能会更改的方法:

...
success : function(data) {
    var $sessid = $('#sessid');
    $sessid.find('option').remove();
    $.each(data, function (index, item) {
        $sessid.append($('<option />').val(item.sessid).text(item.sessid));
    });
    $sessid.val(data[0].sessid).change();
}  
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM