0

我能够加载一个简单的 html 文件,但是当我尝试在加载的 html 中查找元素时,javascript 无法找到该元素。在 IE10 中显示了加载的 html,但标签没有改变。在 Chrome 中,加载不起作用。我是否加载不正确,有没有办法获得对元素的引用?

progress.html 只是在其中包含一个标签,其 id 为“”, "progressLabel"innerText 为“ Loading...”,仅此而已。

我正在创建一个模式对话框,然后加载,然后尝试获取进度标签:

$("#progressbarDiv").dialog({
    resizable: false,
    height: 240,
    width: 500,
    modal: true,
    closeOnEscape: false,
    //disabled: true,
    open: function (event, ui) {
        // Hide close button 
        $(this).parent().children().children(".ui-dialog-titlebar-close").hide();
    },
    buttons: {
        "Ok": {
            text: "OK",
            id: "myOKButton",
            click: function () {
                $(this).dialog("close");
            }
        } 
    }
});
$('#progressbarDiv').load('progress.html');
var testThis = $('#progressLabel');
testThis.text = "...Synchronizing data, please wait...";
4

2 回答 2

4

要访问 AJAX 加载元素中的 HTML,您需要在回调函数中执行 Javascript。

$('#progressbarDiv').load('progress.html',function(){
    // Your script was setting $.text = , but it's a function.
    $('#progressLabel').text("...Synchronizing data, please wait...");
});

$.load(url, callback)是异步的,因此$.load返回时不会加载内容。callback你怎么知道它已经完成了它的$.load处理

您可以$('#progressLabel').text("...Synchronizing data, please wait...");在脚本中的任何位置使用。如果是一个足够小的项目,那没关系。如果您关心维护,您应该构建您的代码,以便它不需要从任何地方全局访问该 div。至少创建一个可以调用的函数,也许它可以按需加载?

/**
 * A simple but slightly better way to set the text from anywhere. 
 * Lazily fetches the progress HTML.
 */
function setProgressString(str) {
    function setText() {
        $('#progressLabel').text(str);
    }

    if ($('#progressLabel').length === 0) {
        $('#progressbarDiv').load('progress.html', setText);
    } else {
        setText();
    }    
}

// Use anytime
setProgressString('...Synchronizing data, please wait...')';
于 2013-04-25T16:09:33.727 回答
0

等到整个页面加载完毕后再尝试访问该元素。

于 2013-04-25T16:07:39.573 回答