2015-04-17 46 views
0

我想附加一個jQuery對話框到它的當前父對象(比方說,因爲它包含輸入,它的父對象是表單中的一個子對象)。 所以,問題在這裏說明:在jQuery對話框中獲取底層元素

http://jsfiddle.net/pprrm4st/2/

我definetly需要找到當前元素的.container和對話附加到它。

appendTo: $(this).closest('.container'), //I thougnt $(this) would be current .element 

否則是否有辦法告訴jQuery不要移動.element無處?

回答

2

this不是該範圍中的元素,您應該注意,沒有函數調用會設置this值。

下面介紹如何使用each環,其中this將是元素來解決它等

$(".element").each(function() { 
    $(this).dialog({ 
     modal: true, 
     autoOpen: false, 
     appendTo: $(this).closest('.container'), 
     buttons: { 
      "I've read and understand this": function() { 
       $(this).dialog("close"); 
      } 
     } 
    }); 
}); 

$('a').click(function(){ 
    $(".element").dialog('open'); 
}); 

FIDDLE

+0

謝謝。好一個! – VladRia

0

,如果你不想這也做的伎倆有一個循環:

$(".element").dialog({ 
    modal: true, 
    autoOpen: false, 
    buttons: { 
     "I've read and understand this": function() { 
      $(this).dialog("close"); 
     } 
    } 
}).dialog("option", "appendTo", $(".element").closest('.container')); 

$('a').click(function(){ 
    $(".element").dialog('open'); 
}); 

甚至更​​短(和更便宜,因爲你只能遍歷一次DOM尋找.element ):

var elem = $(".element") 

elem.dialog({ 
    modal: true, 
    appendTo: elem.closest('.container'), 
    autoOpen: false, 
    buttons: { 
     "I've read and understand this": function() { 
      $(this).dialog("close"); 
     } 
    } 
}) 

$('a').click(function(){ 
    elem.dialog('open'); 
});