如何在Jquery中从嵌套函数调用变量

时间:2014-10-15 19:28:03

标签: jquery

我希望在方法之外调用时获取chkArray变量的值。

当我从方法外部调用 getValues()。total 时,我收到一条错误消息,因为无法读取未定义的属性总数。

function getValues(){
chkArray = new Array() ;
$("input[type=checkbox]:checked").each(function fire() {
 var total = chkArray.push($(this).val());
console.log(chkArray)    
});
};

请帮助如何在方法之外调用该变量

2 个答案:

答案 0 :(得分:1)

使用此:

  function getValues(){
     var total = new Array() ;
     $("input[type=checkbox]:checked").each(function fire() {
       total.push($(this).val());
      });
   return total;
  };

通话功能

var total= getValues();
console.log(total);

答案 1 :(得分:0)

function getValues() {
  var total = new Array();
  $("input[type=checkbox]:checked").each(function() {
    total.push($(this).val());
  });
  return total;
};

function doSomething() {
  var k = getValues();
  console.log(k);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1
<input type="checkbox" name="myCheckbox" value="1" />
<br />2
<input type="checkbox" name="myCheckbox" value="2" />
<br />3
<input type="checkbox" name="myCheckbox" value="3" />
<br />4
<input type="checkbox" name="myCheckbox" value="4" />
<br />5
<input type="checkbox" name="myCheckbox" value="5" />
<br />
<input type="button" onClick="doSomething()" value="Click me" />

相关问题