我不能从onchange事件调用2个函数

时间:2013-04-16 06:17:17

标签: javascript function javascript-events

我必须通过将上面的文本字段作为输入来调用ajax函数以及调用其他函数来获取另一个值。我希望获得返回,形成该功能。 这是我用来调用2个函数的代码,但只有第一个函数ajax(this)才有效,我在调用ajax函数后得到了返回值,而我没有得到第二个函数的任何返回值。我做错了什么 这是我的代码

<select style="width: 305px;" name="category_id1" id="category_id1" onchange="(function(){ajax('this');return locname('this');})(this)">

我的职能是

 function ajax(control)
{
var loc=document.getElementById('category_id1').value;
//alert(loc);
var req;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
   req=new XMLHttpRequest();
}
else
{// code for IE6, IE5
   req=new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("POST", "ajax.php?&loc="+loc+"", true);
req.send();

req.onreadystatechange=function(){
   if(req.readyState==4&&req.status==200){
       //$(".error").hide();
       result=req.responseText
       alert(result);
       var items = JSON.parse(result);
       //alert(items.length)
       var html = '<option value="">Select</option>';
       for ( var i = 0; i < items.length; i++ ) {
       html += "<option value='" + items[ i ] + "'>" + items[ i ] + "</option>"
     }
     document.getElementById("Ultra").innerHTML = html;
   }
   }
   }
 function locname(control)
 {
 var locName=control.value;
 //alert(locName)
 var json = <?php echo $response ?>;
 var orgName=document.getElementById("category_id").value;
//alert(json);
var html="<option>Select</option>";
var locations;
//alert(json.length);
for(var i=0; i<json.length; i++)
    {
        var item = json[i].name;
        //alert(item);
        if(orgName===item){
            //alert(item)
            locations=json[i].location;
            for(var j=0;j<locations.length;j++){
                var location=locations[j].name;
                //alert(locName)
       if(locName===location)
           {
               //alert(locName);
               var buildings=locations[j].building
               //alert(buildings)
               for(var k=0;k<buildings.length;k++)
                   {
                       var building=buildings[k];
                       //alert(building);
                html=html+"<option value='"+building+"'>"+building+"</option>";
                   }
           }

            }

}
}
document.getElementById("category_id2").innerHTML=html;
}

2 个答案:

答案 0 :(得分:20)

试试:

onchange="ajax(this);locname(this);"

答案 1 :(得分:0)

不要在this附近加上引号。它传递文字字符串而不是变量this的值。

相关问题