我的代码是这样的,我试图用 jQuery 函数的结果填充表单字段。但这不起作用。我在这里做错了什么?它将结果记录到控制台,包括哈希值和数组:
jQuery(document).ready(function() {
new GetBrowserVersion().get(function(result, components){
console.log(result); //a hash
console.log(components); //an array
});
var unique_id = result;
$('#unique_id').val(unique_id);
});
我得到的是这样的:
Uncaught ReferenceError: result is not defined
后面是哈希和数组。
您正在关闭该函数,并且该值不可用于(在范围内)用于更新输入:
jQuery(document).ready(function() {
new GetBrowserVersion().get(function(result, components){
console.log(result); //a hash
console.log(components); //an array
var unique_id = result;
$('#unique_id').val(unique_id);
});
});
顺便说一句 - 您可以直接在函数中使用参数,而无需创建 result::
的中间变量jQuery(document).ready(function() {
new GetBrowserVersion().get(function(result, components){
console.log(result); //a hash
console.log(components); //an array
$('#unique_id').val(result);
});
});
如果你确实在其他地方需要
result
,你可以使用闭包来获取get()
之外的值。
var result;
new GetBrowserVersion().get(function(r, components){
console.log(r); //a hash
console.log(components); //an array
result = r; // assigns to the result in the enclosing scope, using a closure
});
var unique_id = result;
$('#unique_id').val(unique_id);