2014-02-17 26 views
0

我有一些Javascript应该调用两个函数,但它没有这样做。我怀疑我可能知道为什么,但我不知道如何解决它。这里是我的jQuery:为什么我无法在JavaScript中调用函数?

var is_mobile = false, 
    page = document.location.pathname.match(/[^\/]+$/)[0]; 
$(document).ready(function(){ 
    var ul = $('nav > ul'), 
     li = ul.children('li'), 
     href = li.find('a[href*="'+page+'"]'), 
     is404 = true; 
    if($('#mobile').css('display')=='none') { 
     is_mobile = true;  
    } 
    if(is_mobile) { 
     orderList(); 
     prepareList(); 
    } 
}); 
/************************/ 
/* Reorders the list */ 
/**********************/ 
function orderList() { 
    $(li.find('a[href*="contact.php"]')).removeAttr('style'); 
     //move element to top 
     ul.prepend(href.parent()); 
     if(page != ""){ 
      li.children('a').each(function(){ 
       if (page == $(this).attr('href')) { 
        is404 = false; 
       } 
      }); 
      if (is404) { 
       //if the user is on a page not in the nav, add a 404 link at the top of the nav 
       ul.prepend("<li><a href='404NotFound.php'><icon><img src='images/404-icon.png'></icon>404</a></li>"); 
      } 
     } 
}; 
/**************************************************************/ 
/* Prepares the list to be dynamically expandable/collapsible */ 
/**************************************************************/ 
function prepareList() { 
    $ul.find('li:has(ul)').unbind('click').click(function(event) { 
     if(this == event.target) { 
      $(this).toggleClass('expanded'); 
      $(this).children('ul').toggle('medium'); 
     } 
     return false; 
    }).addClass('collapsed').removeClass('expanded').children('ul').hide(); 

    //Hack to add links inside the cv 
    $('#expList a').unbind('click').click(function() { 
     window.open($(this).attr('href')); 
     return false; 
    }); 
    //Create the button functionality 
    $('#expandList').unbind('click').click(function() { 
     $('.collapsed').addClass('expanded'); 
     $('.collapsed').children().show('medium'); 
    }) 
    $('#collapseList').unbind('click').click(function() { 
     $('.collapsed').removeClass('expanded'); 
     $('.collapsed').children().hide('medium'); 
    }) 
}; 

我怀疑JavaScript可能无法调用的函数,因为他们的jQuery在其中,但如果是这样的话,我就如何解决它毫无本事。顺便说一下,当我在iTouch上查看时,is_mobile正在返回true。任何想法家伙。谢谢!

回答

0

你确定函数没有被调用吗?或者他们被称为但不产生结果?尝试在每个函数中放置一个断点,或者调用console.log(),甚至是一个alert(),这样你就可以看到它们是否被调用。在我看来,他们应该被称为。

但是,我认为你有变量范围的问题。您可以在document.ready()函数内定义变量ulli,但在顶层定义的orderList()prepareList()中引用它们。所以你的变量对你的函数是不可见的。并且,在prepareList()中,您引用$ul,而不是ul$ul根本没有定义,因此当第一次引用时它被作为(n空)全局来处理。

尝试用is_mobile沿定义的所有功能外,这些变量,然后用vardocument.ready()功能不重新定义它们,只是给它们赋值存在。或者,如果您不喜欢全局变量,则将所有这些变成一个模块 - 但您仍然需要使变量对模块中的所有函数都可见,或者将它们作为参数传递给函数。

+0

它们必须在'document.ready()'函数中设置,因为它们是基于HTML中的元素设置的。 – LarryK

+0

是的,它们必须在ready()函数中设置 - 初始化。但是他们不必在那里宣布,他们在哪里隐藏了其他脚本。 (我看到我写了'defined';'declare'更准确。)如果它们在'ready()'之外声明,它们对'ready()'脚本可以设置它们的值以及其他函数来读取这些值。或者,这些函数可以在'ready()'中移动,因此它们与被接受的答案中提出的范围相同。 – Val

相关问题