javascript 如何处理从 AJAX 调用生成的下拉列表事件

yftpprvb  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(126)

我有一个下拉框,下拉框中的值是通过 AJAX 调用生成的。我的问题是当值发生变化时,如何处理下拉框的事件,或者如何调用onChange()中的函数。我是JavaScript新手。这是我的代码:

YAHOO.util.Event.addListener(window, "load", function() {
    YAHOO.util.Connect.asyncRequest('GET', '/mcm/litter/litterSequenceList', {        
        success:function(o) {
            data = YAHOO.lang.JSON.parse(o.responseText);
            generateTablesList(data);   
        },
        failure:function(o) {
            alert(o.statusText);
        },
        scope:this
    }));

        
    function generateTablesList(data) {
        var list ="<select style='width:125px' id='litterSequences' name='litterSequences'>";
        var opt;    
        opt = "<option value='null'></option>";
        for (var i=0; i<data.length; i++) {
            opt =  "<option value="+data[i]+">";
            opt = opt+data[i];
            opt = opt+"</option>";  
            list = list+opt;    
        }           
        list = list+"</select>";
        var listObj = document.getElementById("litterSequence");
        if(listObj) {
            listObj.innerHTML = list;
        } 
    }
});
hujrc8aj

hujrc8aj1#

我认为最简单的方法是:

YAHOO.util.Event.addListener(window, "load", function() {
    YAHOO.util.Connect.asyncRequest('GET', '/mcm/litter/litterSequenceList', {        
        success:function(o) {
            data = YAHOO.lang.JSON.parse(o.responseText);
            generateTablesList(data);   
        },
        failure:function(o) {
            alert(o.statusText);
        },
        scope:this
    }));

    function generateTablesList(data) {
        var list ="<select style='width:125px' id='litterSequences' name='litterSequences'>";
        var opt;    
        opt = "<option value='null'></option>";
        for (var i=0; i<data.length; i++) {
            opt =  "<option value="+data[i]+">";
            opt = opt+data[i];
            opt = opt+"</option>";  
            list = list+opt;    
        }           
        list = list+"</select>";
        var listObj = document.getElementById("litterSequence");
        if(listObj) {
            listObj.innerHTML = list;
        } 

        var dropDown = document.getElementById("litterSequences");
        dropDown.onchange = function() {
            // Whatever you need to do
        };
    }
});

当然,您可以在其他地方定义处理程序,例如:

function onLitterSequencesChange() {
    // Your code
}

以及:

(...)
var dropDown = document.getElementById("litterSequences");
dropDown.onchange = onLitterSequencesChange;
(...)

相关问题