在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 } }
因为我需要评估数组中的所有项目,如果只有一项是真的,那么在$.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'); } };
解决方法
或多或少,正是你现在拥有的……你只需要将数据传递给函数(通过让它接受一个参数).见
a live example.
var some_function = function(array) { // false by default var something = false; $.each(array,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]);