Jquery函数暂时工作,然后根本不工作?

sto*_*yri 0 javascript jquery

我已将此幻灯片机制应用于页面,并且它运行良好一段时间.我记不起任何改变,但现在它将无法正常运作.

这是代码:

$(document).ready(function () {
    var hash = window.location.hash.substr(1);
    var href = $('#nav li a').each(function () {
        var href = $(this).attr('href');
        if (hash == href.substr(0, href.length)) {
            var toLoad = hash + '.html #content';
            $('#content').load(toLoad)
        }
    });
    $('#nav li a').click(function () {
        $("#story_pane").animate({
            marginLeft: 360
        }, 250);
        $("#main_content").animate({
            marginLeft: -600,
            opacity: 0.3
        }, 250);
        $("#main_content").css();
    });
    alert("test");
    var toLoad = $(this).attr('href') + ' #content';
    $('#content').hide(1, loadContent);
    $('#load').remove();
    $('#story_pane').css("display", "block");
    $('#story_pane').append('<span id="load"></span>');
    $('#load').fadeIn(1);
    window.location.hash = $(this).attr('href').substr(0, $(this).attr('href').length - 5);

    function loadContent() {
        $('#content').load(toLoad, '', showNewContent())
    }

    function showNewContent() {
        $('#content').show(1, hideLoader());
    }

    function hideLoader() {
        $('#load').hide();
    }
    return false;
});
Run Code Online (Sandbox Code Playgroud)

只有"测试"警报正确执行,我一直在寻找我忘记关闭的任何括号,或其他语法问题,但我有点死路一条.我确实备份了文件,但这是最后的选择,万一我无法解决这个问题.

编辑 - 现在工作,我删除 $("#main_content").css();并添加了一个修复它的点击功能

Poi*_*nty 5

改变这个:

    function loadContent() {
        $('#content').load(toLoad,'',showNewContent) // remove the "()" here
    }
Run Code Online (Sandbox Code Playgroud)

调用 ".load ()"编码的方式,在加载开始时调用 "showNewContent",而不是在完成时调用."showNewContent"函数本身也是如此:

    function showNewContent() {
        $('#content').show(1,hideLoader); // again, remove "()" from "hideLoader"
    }
Run Code Online (Sandbox Code Playgroud)

重要的是要明确区分函数时将名称作为需要回调的API的参数传递给实际调用函数的过程.在这些情况下,您需要对函数的引用.(是的,函数调用可以返回对函数的引用,但这不是这里发生的事情.)

编辑 - 你将在这里遇到的另一个重要问题是,基于导航状态获取当前相关页面的初始调用".load()"几乎肯定无法在其余代码之前完成跑.如果对初始调用"load()"所加载的内容进行初始化有任何依赖关系,那么它还不会在DOM中.您可以通过将"ready"处理程序的其余部分中的所有代码填充到该初始".load()"的完成处理程序中来解决此问题.

再次编辑 - 确定另一个问题是这行代码,就在"alert()"之后:

var toLoad = $(this).attr('href') + ' #content';
Run Code Online (Sandbox Code Playgroud)

你期望this在这一点上是什么?我认为 jQuery将设置this为引用"文档"对象,但您将无法从中获取任何"href"属性.也许你想要"window.location.href"吗?我完全不确定你要完成什么.