我有一些Javascript应该调用两个函数,但它没有这样做。我怀疑我可能知道为什么,但我不知道如何解决它。这是我的jQuery:
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 :(得分:0)
你确定这些功能没有被调用吗?或者他们被召唤但是没有产生结果?尝试在每个函数中放置一个断点,或调用console.log(),甚至是alert(),这样你就可以看到它们是否被调用。在我看来他们应该被称为。
但是,我认为您在变量范围方面存在问题。您可以在document.ready()函数中定义变量ul
和li
,但可以在orderList()
和prepareList()
中引用它们,它们是在顶层定义的。因此,您的变量对您的函数不可见。而且,在prepareList()
中,您引用的是$ul
,而不是ul
。 $ul
根本没有定义,因此在首次引用时它被定义为(n空)全局。
尝试在is_mobile
之后的所有函数之外定义这些变量,然后不要在var
函数中使用document.ready()
重新定义它们,只需在那里为它们赋值。或者,如果您不喜欢全局变量,请将所有这些包装到模块中 - 但您仍然需要使变量对模块中的所有函数可见,或者将它们作为参数传递给函数。