【问题标题】:JQuery myArray[myVarriable] is undefined, even though i've defined itJQuery myArray[myVarriable] 未定义,即使我已经定义了它
【发布时间】:2011-07-03 14:11:05
【问题描述】:

好的,让我告诉你我想在这里做什么, 有 4 个对象,类似于这个:

var links = {name: "Links", id: "links", index: 0};

我将它们放在一个数组中:

var pages = [links,about,projects,contact];

我创建了这个函数:

function active_page(selected){
  var active = 0;
  $("[id="+pages[selected].id+"]").show();
}

然后我在

中运行active_page(0)
$(function(){
  active_page(active);
});

我得到了这个错误:

pages[selected] is undefined

整个 .js 文件在这里: http://pastebin.com/2rBWiVJF

我得到的错误在第 26 行

感谢您的宝贵时间

【问题讨论】:

    标签: jquery arrays object undefined


    【解决方案1】:

    这是一个常见问题。实际问题在于您的 clicked() 函数。

    for 循环不会创建新的范围,因此您总是引用同一个 i 变量,它将在循环之后保存最新的值。

    function clicked() {
        for (var i = 0; i < pages.length; i++) {
            $("[id=" + pages[i].id + "_btn]").mousedown(function (e) {
                if (e.which == 1) {
                    // the "i" passed is always going to be the same as "pages.length"
                    active_page(i);
                    active = i;
                }
            });
        }
    }
    

    在 JavaScript 中确定变量范围的唯一方法是在函数中。所以你应该将i 传递给一个新的函数调用,以便对其进行范围。

    function clicked() {
        // used to scope the value of "i", and return a function
        //     that references it.
        function createHandler(this_i) {
            return function (e) {
                if (e.which == 1) {
                    active_page(this_i);
                    active = this_i;
                }
            }
        }
        for (var i = 0; i < pages.length; i++) {
            $("[id=" + pages[i].id + "_btn]").mousedown(createHandler(i));
        }
    }
    

    【讨论】:

      【解决方案2】:
      var active = 0;
      var pages  = [{name: "Links", id: "links"}, 
                {name: "About", id: "about"}, 
                {name: "Projects", id: "projects"}, 
                {name: "Contact", id: "contact"];
      
      function active_page(selected){
         $('#' + pages[selected].id).show();
      }
      
      $(function(){
        active_page(active);
      });
      

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 1970-01-01
        • 2020-08-25
        • 2017-10-19
        • 2021-01-29
        • 2021-03-11
        • 2019-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多