2016-07-08 58 views
1

我倒過來尋找這個答案(在我看來似乎是一個看似簡單的問題)。我想動態地創建一個jQuery對話框,但我想讓對話框的文本/正文包含一個href - 需要用對話框動態創建。例如:如何將動態html添加到jQuery對話框的文本字段?

var newDiv = $(document.createElement('div')); 
    var j = 1; 

    newDiv.dialog({ 
    resizable: false, 
    height:240, 
    modal: true, 
    text: '<a href="html://test.com">test link' + j + ' within a dialog body</a>', 
    title: "MyDialog", 
    buttons: { 
     "Add Related": function() { 
      $(this).dialog("close"); 
      window.location = "addRelated.php?id="+id;     
     }, 
     Cancel: function() { 
      $(this).dialog("close"); 
     } 
    } 
}); 

該文本參數似乎只採取文本。有人可以幫我嗎?謝謝。因此

var newDiv = $('<div><a href="html://test.com">test link' + j + ' within a dialog body</a></div>'); 
newDiv.dialog(...); 

,否定需要使用無證文本屬性:你使用jQuery與jQuery.ui

+0

兩個答案都很好。謝謝你們倆!我不知道哪一個可以作出主要答案,所以我提出了更爲詳細的答案。 – Tornado

回答

1

創建一個div並添加文本它的方法是:

var j = 1; 
var newDiv = $('<div/>').append('<a href="html://test.com">test link' + j + ' within a dialog body</a>'); 

的jQuery UI的對話框具有文本屬性僅對定義按鈕標籤(見:option-buttons)。

所以我的片段是:

$(function() { 
 
    var j = 1; 
 
    var newDiv = $('<div/>').append('<a href="html://test.com">test link' + j + ' within a dialog body</a>'); 
 

 
    newDiv.dialog({ 
 
    resizable: false, 
 
    height:240, 
 
    modal: true, 
 
    title: "MyDialog", 
 
    buttons: { 
 
     "Add Related": function() { 
 
     $(this).dialog("close"); 
 
     window.location = "addRelated.php?id="+id; 
 
     }, 
 
     Cancel: function() { 
 
     $(this).dialog("close"); 
 
     } 
 
    } 
 
    }); 
 
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/> 
 
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

一種不同的方式來實現這一目標是基於open event

$(function() { 
 
    var newDiv = $('<div/>'); 
 
    var j = 1; 
 

 
    newDiv.dialog({ 
 
    resizable: false, 
 
    height:240, 
 
    modal: true, 
 
    title: "MyDialog", 
 
    buttons: { 
 
     "Add Related": function() { 
 
     $(this).dialog("close"); 
 
     window.location = "addRelated.php?id="+id; 
 
     }, 
 
     Cancel: function() { 
 
     $(this).dialog("close"); 
 
     } 
 
    }, 
 
    open: function(event, ui) { 
 
     $(this).append('<a href="html://test.com">test link' + j + ' within a dialog body</a>'); 
 
    } 
 
    }); 
 
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/> 
 
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

1

假設,你可以在div創建所有的HTML。

相關問題