[英]jQuery $.each variable Scope
Having a scope issue problem with a $.each
loop in jQuery . 在jQuery中有一个$.each
循环的范围问题。 How can I get a global variable in a function to set in a loop or at least pass something out of it? 如何在函数中获取一个全局变量来设置循环或至少传递一些东西呢?
var some_function = function() {
// false by default
var something = false;
$.each(array, function(key, val) {
if (val == 'something')
{
// even if one item evaluates true I need to check outside of the loop
something = true;
}
});
if (something == true)
{
// do something else, but always false
}
}
Since I'm needing to evaluate all items in the array, and if only one is true
, then do something additional, outside of the $.each
. 因为我需要评估数组中的所有项目, 如果只有一项是 true
,那么在$.each
之外做一些额外的$.each
。
Update 更新
$(document).ready(function () {
something();
$(':radio').trigger('change');
)};
Ok, so this is the actual code. 好的,这是实际的代码。 It's alerting 'false' at the bottom and then alerts 'hello' twice, as if it's going in reverse order. 它在底部警告“假” ,然后两次警告“你好” ,好像它按相反顺序发出。
var something = function() {
var q_radios = {
'radio1' : 'radio1_selector',
'radio2' : 'radio2_selector',
};
var show_me = false;
$.each(q_radios, function(name, q_selector) {
$('input:radio[name=' + q_selector + ']').change(function() {
show_me = true;
alert('hello');
});
});
if (show_me == true)
{
alert('yes');
}
else
{
alert('false');
}
};
More or less, exactly what you have now … you just need to pass the data into the function (by letting it accept an argument). 或多或少,正是你现在拥有的......你只需要将数据传递给函数(通过让它接受一个参数)。 See a live example . 查看实时示例 。
var some_function = function(array) {
// false by default
var something = false;
$.each(array, function(key, val) {
if (val == 'something') {
something = true;
}
});
if (something == true) {
alert("There was a something");
} else {
alert("There wasn't a something");
}
};
some_function([1,2,3]);
some_function([1,"something",3]);
I recommend native Array iteration methods: 我推荐本机Array迭代方法:
var something = array.some(function ( val ) {
return val === 'something';
});
Here, something
will be true
if at least one array element has the value 'something'
. 如果至少有一个数组元素的值为'something'
, something
将是true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.