[英]jQuery $.each variable Scope
在jQuery中有一個$.each
循環的范圍問題。 如何在函數中獲取一個全局變量來設置循環或至少傳遞一些東西呢?
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
}
}
因為我需要評估數組中的所有項目, 如果只有一項是 true
,那么在$.each
之外做一些額外的$.each
。
更新
$(document).ready(function () {
something();
$(':radio').trigger('change');
)};
好的,這是實際的代碼。 它在底部警告“假” ,然后兩次警告“你好” ,好像它按相反順序發出。
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');
}
};
或多或少,正是你現在擁有的......你只需要將數據傳遞給函數(通過讓它接受一個參數)。 查看實時示例 。
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]);
我推薦本機Array迭代方法:
var something = array.some(function ( val ) {
return val === 'something';
});
如果至少有一個數組元素的值為'something'
, something
將是true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.