基本的javascript范围

时间:2015-01-27 03:40:55

标签: javascript jquery

我在此代码中收到错误:

$(document).ready(function () {


    var appContainer = {
        apps: new Array()
    };


    $("funcList div").each({
       appContainer.apps.push("testing"); // this does not work, why?
    })

    appContainer.apps.push("testing");
    )


});

appContainer是否超出了每个方法的范围? 这是我得到的错误:enter image description here

感谢

1 个答案:

答案 0 :(得分:1)

这里有多个语法错误,如下所示,您还需要查看选择器funcList divfuncList是ID还是类,如果是,请使用适当的选择器。< / p>

$(document).ready(function () {
    var appContainer = {
        apps: new Array()
    };

    //need to pass a function as the argument here
    $("funcList div").each(function () {
        appContainer.apps.push("testing"); // this does not work, why?
    })

    //extra ) here
    appContainer.apps.push("testing");

    console.log(appContainer)
});

演示:

$(document).ready(function() {
  var appContainer = {
    apps: new Array()
  };

  //need to pass a function as the argument here
  $("funcList div").each(function() {
    appContainer.apps.push("testing"); // this does not work, why?
  })

  //extra ) here
  appContainer.apps.push("testing");

  console.log(appContainer)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<funcList>
  <div></div>
  <div></div>
</funcList>