如何运行多个函数然后执行回调

问题描述

| 我再一次“沉迷”于javascript和jQuery的黑暗艺术中,而对我实际上在做什么却一无所知。我所知道的是,通过抄写其他代码的一部分并对其进行了一些修改,我设法使自己的代码起作用,并且经过大量的咒骂,它以某种方式工作了。 下面是我的一段代码,它可以正确构建并显示一个动态选择框,其中包含从mySQL查询返回的值。当用户从列表中选择一个项目时,该代码将成功运行一个功能,该功能显示与该项目相关的地图。 我实际上需要做的是还运行代码以首先显示查询所返回的认/顶部项目的地图,然后在每次选择新项目时都应运行该函数显示新选择的地图。 我希望解释已经很清楚了,但如果没有的话,请随时批评我。 非常感谢, 抢。
 $(document).ready(function() {
$(\'#selecthere\').load(\'/temp/PHP_script.PHP?r=\'+ random,function () 
 { //callback
$(\'select\',this).change(function () { //catch onchange event of select
//call your function here,pass the selected value
initialize($(this).val());
});
});
});
    

解决方法

        (根据下面的评论进行编辑。) 据我了解,
initialize(val)
是绘制与
val
相关联的地图的函数,并且您想在页面加载时运行它,而default2 the缺省是选择框中的任何内容。为此,您可以像这样在
ready
函数中添加函数调用:
$(document).ready(function(){
    var random = Math.random();
    // load contents of php script into #selecthere element
    $(\'#selecthere\').load(\'/temp/php_script.php?r=\'+ random,function (){ 
       // the contents of the php script are now loaded
       // go ahead and call initialize() on the value that is selected by default
       initialize($(\'select[name=title]\').val());
       // attach a function to fire when select element is changed
       $(\'select[name=title]\').change(function () { 
           // here \'this\' refers to the select element
           // call initialize() with the value of select element
           initialize($(this).val());
       });
    });
});
希望我能理解。     ,        看看JQuery Events API。这样,您可以在发生不同的用户交互时运行功能。小例子:
$(\'#foo\').bind(\'click\',function() {
  alert(\'User clicked on \"foo.\"\');
});
单击ID为#foo的项目时,它将运行。