以下代码是一个非常简单且完整的JQuery对话框。一切正常。

问题如js1.js标题中所述:(请参阅其注释)

它总是尝试通过调用horsedlgcontainer.load('page2.html');来加载页面,而不会命中else horsedlg.dialog('open');语句。

有什么想法吗?非常感谢你!

page1.html ...

<!DOCTYPE html>
<head>
    <link href="Site.css" rel="stylesheet" type="text/css" />
    <link href="jquery-ui-1.8.21.custom.css" rel="Stylesheet" type="text/css" />
    <script src="jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
    <script src="js1.js" type="text/javascript"></script>
</head>
<body>
<div id="horse-link">
    [<a id="horse-link-show-dialog">Click Me</a>]
</div>
<div id="horse-link-dialog-container"></div>
</body>


page2.html ...

<script src="js2.js" type="text/javascript"></script>
<div id="horse-dialog" title="Horse!">
Q: When is a horse not a horse?<br />
A: It depends, when a white horse is not a horse.<br />
</div>


js1.js ...

$(document).ready(function () {
    var horselnk = $('#horse-link'),
        horsedlg = $('#horse-dialog'),
        horsedlgcontainer = $('#horse-link-dialog-container'),
        showdlgbtn = $('#horse-link-show-dialog');
    $.ajaxSetup({ cache: false });
    showdlgbtn.click(showHorseDialog);
    function showHorseDialog() {
        if (horsedlg.length==0)
            horsedlgcontainer.load('page2.html');
        else  //to improve performance, open it again, don't load the same page
            horsedlg.dialog('open'); //Why never come here?!?
    }
});


js2.js ...

$(document).ready(function () {
    var horsedlg = $('#horse-dialog'),
        horselnk = $('#horse-link');
    horsedlg.dialog({
        modal: true, autoOpen: true, resizable: false,
        height: 500, width: 350, closeOnEscape: true,
        show: {effect:'puff',percent:150,duration:250},
        hide: {effect:'puff',percent:110,duration:250}
    });
});

最佳答案

您只评估一次horsedlg = $('#horse-dialog'),并且它是在内容加载之前进行的,因此其.length属性始终为零。



我怀疑在加载对话框内容时,在加载辅助JS文件时也会遇到问题。单个JS文件会更干净:

$(document).ready(function () {

    var options = {
        modal: true, autoOpen: true, resizable: false,
        height: 500, width: 350, closeOnEscape: true,
        show: {effect:'puff',percent:150,duration:250},
        hide: {effect:'puff',percent:110,duration:250}
    };

    var loaded = $.Deferred();
    $('#horse-link-show-dialog').on('click', function() {
        var state = loaded.state();
        if (state === 'resolved') {
            $('#horse-dialog').dialog('open');
        } else if (state === 'pending') {
            // do nothing
        } else {
            $('#horse-link-dialog-container').load('page2.html')
               .fail(loaded.reject);
               .done(function() {
                    $('#horse-dialog').dialog(options);
                    loaded.resolve();
                });
            });
        }
    });
});


这使用jQuery延迟对象来指示对话框是否已完成加载。

注意:代码未经测试-jsfiddle不适用于测试AJAX。

09-20 04:36