您现在的位置是:首页 > 电脑技术查询 > web开发

js 先后执行有关问题 在线急等

编辑:chaxungu时间:2022-10-02 23:16:20分类:web开发

js 先后执行问题 在线急等!
HTML code<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=gbk" /><title>本地搜索的数据接口</title><script src="http://api.map.baidu.com/api?key=46ce9d0614bf7aefe0ba562f8cf87194&v=1.1&services=true" type="text/javascript"></script> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script></head><body ><div style="width:520px;height:340px;border:1px solid gray" id="container"></div> <input id="log" type="text" /> <input id="Button1" type="button" onclick="sbutton()" value="搜索" /><input id="Text1" type="text" /><script type="text/javascript"> var map = new BMap.Map("container"); map.centerAndZoom(new BMap.Point(120.165941, 30.294973), 11); function search() { var options = { onSearchComplete: function (results) { // if (local.getStatus() == BMAP_STATUS_SUCCESS) { try { document.getElementById("log").value = results.getPoi(0).point.lng; } catch (e) { return 0; } // } } }; var local = new BMap.LocalSearch(map, options); local.search(document.getElementById("Text1").value); } function sbutton() { search(); alert(document.getElementById("log").value) }</script></body></html>

function sbutton() {

search();//我想先等这段执行完毕之后在执行下面一句
alert(document.getElementById("log").value)

}

------解决方案--------------------
你这样已经实现了啊。。
------解决方案--------------------
1.简单处理:把alert(document.getElementById("log").value)放到onSearchComplete方法尾部,这种方法简单,但写死了不好修改。
2.正确处理:使用回调,异步执行的函数,要控制与主线程的先后次序一般都使用回调
<script type="text/javascript">
var map = new BMap.Map("container");
map.centerAndZoom(new BMap.Point(120.165941, 30.294973), 11); function search(callBack) {//callBack为回调函数

var options = {
onSearchComplete: function (results) {
// if (local.getStatus() == BMAP_STATUS_SUCCESS) {
try {
document.getElementById("log").value = results.getPoi(0).point.lng;

}
catch (e) {
return 0;
}
// }
callBack();
}
};

var local = new BMap.LocalSearch(map, options);

local.search(document.getElementById("Text1").value);
}

function sbutton() {
function callBack()
{
alert(document.getElementById("log").value)
}
search(callBack);//使用回调可以很方便的修改要执行的代码
}
</script>

------解决方案--------------------
设一全局变量 var flag=false;
让search()函数返回值true;

shutton(){
var btmp= search();
if(btmp){
alert(">>");
}
}
------解决方案--------------------