无法从事件中访问功能

时间:2011-11-07 16:31:01

标签: javascript jquery jquery-ui

我对javascript很新,我不明白这个问题:

$(function() {
    var $tab_title_input = $( "#tab_title"),
    $tab_content_input = $( "#tab_content" );
    var tab_counter = 0;
    var editors = {};
    var tab_current = 0;

    // tabs init with a custom tab template and an "add" callback filling in the content
    var $tabs = $( "#tabs").tabs({
        tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
        add: function( event, ui ) {
            var tab_content = $tab_content_input.val() || "Tab " + tab_counter + " content.";
            $( ui.panel ).append("<div id=\"editor" + tab_counter + "\" class=\"editor\">" + tab_content + "</div>");
            adjust_size();
            tab_current = ui.index;
            editors[tab_current] = ace.edit("editor" + tab_counter);
            },
        show: function( event, ui ) {
            adjust_size();
            tab_current = ui.index; // zero-based index
            editors[tab_current].resize();
        },
        select: function( event, ui ) {
            adjust_size();
            tab_current = ui.index; // zero-based index
            },

    });

问题是这行代码:

editors[tab_current].resize();

打破一切告诉Uncaught TypeError: Cannot call method 'resize' of undefined

但编辑editors[tab_current].resize()在添加事件中已明确定义,alert(tab_current)为我提供了正确的结果。

2 个答案:

答案 0 :(得分:1)

我打赌editors[tab_current]返回undefined的钱。

您的alert(tab_current)可能会返回正确的值,但这并不意味着editors的元素与其对应。使用alert(editors[tab_current])对其进行测试,如果显示undefined,则检查元素是否设置正确。

答案 1 :(得分:0)

我可以立即看到两种调查途径:

  1. ace.edit("editor" + tab_counter)返回什么?是总是使用resize方法返回一个对象还是有时会返回undefined?

  2. 对于add的任何值,始终在show之前调用tab_current吗?