2012-08-12 71 views
2

此代碼作品完美,除了 - 對話窗口如我所料X毫秒後不會關閉......執行jQuery UI的對話框 - X秒後關閉

setTimeout功能(我把警報()存在和它的工作...),所以我認爲問題是與$("#alert div").dialog('close');但我不知道什麼是錯的...

if ($("#alert").length) { 
    var title; 
    if ($("#alert span").length) { 
     title = $("#alert span").text(); 
    } 
    $("#alert div").dialog({ 
     title: title, 
     modal: true, 
     open: function() { 
      setTimeout(function() { 
       $("#alert div").dialog('close'); 
      }, 2000); 
     } 
    }); 
} 

編輯: 如果有幫助,這裏是HTML:

<div id="alert"> 
    <span>Password change</span> 
    <div>Password was successfully changed.</div> 
</div> 

已解決!如果有人有想法,爲什麼我的代碼無法正常工作,會很棒...

+0

看到我更新的答案與解釋爲什麼你所期望的工作是什麼沒有。 – j08691 2012-08-12 20:39:48

回答

10

您有一個範圍界定問題。試試這個jsFiddle example

if ($("#alert").length) { 
    var title; 
    if ($("#alert span").length) { 
     title = $("#alert span").text(); 
    } 
    $("#alert div").dialog({ 
     title: title, 
     modal: true, 
     open: function() { 
      var foo = $(this); 
      setTimeout(function() { 
       foo.dialog('close'); 
      }, 2000); 
     } 
    }); 
}​ 

之所以發生這種情況,而不是工作像你想的那樣,是由於你引用成爲對話的目標DIV的方式,而jQuery UI的構建方式對話。如果您查看開發者控制檯,您會看到jQuery將您的div從DOM中的原始位置中取出,因此不再可以引用#alert div,因爲它不再是#alert的子代。如果您已經爲該div分配了自己的ID,它將按預期工作,並且您不需要臨時變量來引用它。

+1

爲什麼要在這裏確定一個問題?這並不像他想在setTimeout回調中使用'this'這樣的回覆 – Hubro 2012-08-12 20:23:10

+1

謝謝@ j08691!奇蹟般有效。 – Martin 2012-08-12 20:31:38

+0

@Codemonkey - 查看我的更新的原因。讓我知道你是否需要更多細節。 – j08691 2012-08-12 20:44:10

0

測試和工作現場演示:

http://jsfiddle.net/oscarj24/q6tD9/2/

我覺得這種方式較好:

jQuery.fn.exists = function(){return this.length>0;} 

$(function() { 
    if($('#alert').exists()){ 
     var modal = $('#alert div'); 
     modal.dialog({ title: $('#alert span').text(), modal: true }); 
     var opened = modal.dialog('isOpen'); 
     if(opened){ 
      setTimeout(function(){ 
       modal.dialog('close'); 
      }, 2000); 
     } 
    } 
});​