本文介绍了jQuery全局变量可在任何地方使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始怀疑jquery易于使用且灵活.我有这个:
I am starting to doubt that jquery is easy to use and flexible.I have this:
var prodata=[];
var request = $.get("proDB.txt", function(data) {
var lines=data.split(/\n/);
var numberofmodels=lines.length-2;
//var prodata=[];
var i;
prodata.push(0);
var fieldnames=lines[0].split(/\t/);
for (i = 1; i < lines.length-1; ++i) {
var fields=lines[i].split(/\t/);
prodata.push(i);
var j;
prodata[i]={};
for (j = 0; j < fields.length; ++j) {
//prodata[i][fieldnames[j]]=fields[j];
var str=fieldnames[j];
prodata[i][str]=fields[j];
}
}
//FILL THE DROPDOWN LIST
var options = '';
for (i = 1; i < lines.length-1; ++i) {
if (prodata[i]['name'].indexOf("elly") >= 0) {
var iselected = i;
}
options += '<option label="bla" value="' + prodata[i]['id'] + '">' + prodata[i]['name']+', '+prodata[i]['brand']+', '+prodata[i]['model']+'</option>';
}
$("#userchosenpromodel").html(options);
//SELECT DEFAULT OPTION
$('#userchosenpromodel option[value="' + prodata[iselected]['id'] + '"]').attr("selected", "selected");
}, 'text'); //$.get
在这样定义之后,我想在代码的下面使用proId
:
I would like to use proId
, lower in my code, after it's been defined like that:
//SUBMIT FORM
$('#submitbutton').click(function(e) {
e.preventDefault();
request.done(function(){
proId=$('#userchosenpromodel option[selected="selected"]').val();
proId=parseInt(proId);
computeUserDimensions(prodata[proId]);
});
});
console.log(proId);
如何?
与prodata
相同的问题...我有request.done
我无法摆脱
Same problem for prodata
...I have request.done
that I can't get rid of
谢谢
推荐答案
您对jQuery没问题,但基于异步/事件的逻辑却没有问题.
You don't have a problem with jQuery but with asynchronous/event based logic.
您不能同步使用异步函数的返回值.您必须在回调或从回调中调用的函数中使用结果:
You can't synchronously use the return of an asynchronous function. You must use the result in the callback or in a function you call from the callback :
request.done(function(){
var proId=$('#userchosenpromodel option[selected="selected"]').val();
console.log(proId);
});
这篇关于jQuery全局变量可在任何地方使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!