如何处理从ajax调用生成的下拉事件

时间:2011-05-20 12:07:46

标签: javascript javascript-events

我有一个下拉框,下拉列表中的值是从ajax调用生成的。 我的问题是如何在值更改时处理下拉列表事件。或者如何在onChnage()中调用函数。我刚认为是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;
        } 
    }
});

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是:

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;
(...)