关于js全局变量和setTimeout

时间:2022-05-28 20:30:43

没有加var的js变量,在方法体内也会算做全局变量

loadSelect("006","level","cust_level.dict_id"<s:if test="#customer.cust_level!=null">,<s:property value="#customer.cust_level.dict_id"/></s:if>);
loadSelect("001","industry","cust_industry.dict_id"<s:if test="#customer.cust_level!=null">,<s:property value="#customer.cust_industry.dict_id"/></s:if>);
loadSelect("009","source","cust_source.dict_id"<s:if test="#customer.cust_level!=null">,<s:property value="#customer.cust_source.dict_id"/></s:if>);



function loadSelect(typecode,positionId,selectname,selectId){
$select=$("<select name="+selectname+"></select>")
$select.append("<option value=''>请选择</option>");
$("#"+positionId).append($select)
$.post(
"${pageContext.request.contextPath}/baseDictAction_list",
{dict_type_code:typecode},
function(data){
$(data).each(
function(i, json) {
/* selected='selected' */
$option = $("<option   value=" + json['dict_id'] + ">"
+ json['dict_item_name'] + "</option>")
if (json['dict_id'] == selectId) {
$option.attr("selected", "selected")
}
$select.append($option)

});
},"json");
}

ajax是异步调用的

创建3个下拉列表调用之后产生了所有json选项都在同一个下拉列表的情况,这是因为ajax异步调用,最后才执行.然后所有option都到了最后的全局变量$select(对应为一个下拉列表)


尝试不加var在前面,就使用全局变量来完成任务


setTimeout(loadSelect("006","level","cust_level.dict_id"<s:if test="#customer.cust_level!=null">,<s:property value="#customer.cust_level.dict_id"/></s:if>),4000);
setTimeout(loadSelect("001","industry","cust_industry.dict_id"<s:if test="#customer.cust_level!=null">,<s:property value="#customer.cust_industry.dict_id"/></s:if>),8000);
setTimeout(loadSelect("009","source","cust_source.dict_id"<s:if test="#customer.cust_level!=null">,<s:property value="#customer.cust_source.dict_id"/></s:if>),12000); 

来解决问题,然后解决问题失败.因为setTimeout里面要传的参数为函数名(例如app),而不是(app()) 

如果想要传参数   可以使用 setTimeout( "app("+"1,2)",100)



最后方法

   setTimeout("loadSelect("+"'006','level','cust_level.dict_id'<s:if test='#customer.cust_level!=null'>,<s:property value='#customer.cust_level.dict_id'/></s:if>)",100);
setTimeout("loadSelect("+"'001','industry','cust_industry.dict_id'<s:if test='#customer.cust_level!=null'>,<s:property value='#customer.cust_industry.dict_id'/></s:if>)",200);
setTimeout("loadSelect("+"'009','source','cust_source.dict_id'<s:if test='#customer.cust_level!=null'>,<s:property value='#customer.cust_source.dict_id'/></s:if>)",300); 


完美解决问题