jquery ui - modal dialog (better way to create content of modal?)

这一生的挚爱 提交于 2019-12-10 23:14:57

问题


Is there a way to define the modal content in the javascript, rather than always having to have an element on the page and create the dialog from that?

It has the title option, so I can 'dynamically' create a modal title, but what about the actual content? Like say I need it to say, "you are going to delete image #539". Rather than creating a modal for every possible image - or even from creating the element and then making the dialog from that.

There's got to be a better way.


回答1:


You could try something like this:

HTML

<button id='diag1'>First dialog</button>
<button id='diag2'>Second dialog</button>

Javascript

var diag = $('<div id="myDialog" title="Testing!"><span id="dialogMsg"></span></div>');

diag.dialog({
    autoOpen: false,
    modal: true
});

$('#diag1').click(function() {
    $('#dialogMsg').text("Message for dialog 1.");
    diag.dialog("open");
});

$('#diag2').click(function() {
    $('#dialogMsg').text("Message for dialog 2");
    diag.dialog("open");
});

Demo here.




回答2:


Here's another solution, a bit more dynamic:

function showError(errorTitle, errorText) {

    // create a temporary place to store our text
    var window = $('<div id="errorMessage" title="' + errorTitle + '"><span id="dialogMsg">' + errorText + '</span></div>');

    // show the actual error modal
    window.dialog({
        modal: true
    });
}

Then when you need to call the error modal simply do:

showError("Error-Title", "Error message here");

You can imagine adding more parameters to the function to control the width, height, etc.

Enjoy!




回答3:


Thank you Scott. I have added a title attribute for the dialog:

...

var diag = $('<div id="myDialog" title=""><div id="dialogMsg"></div></div>');

...

$('#diag1').click(function() {
    $('#dialogMsg').html('<div class="dialog-body">Message for dialog 1</div>');
    $("#myDialog").dialog({title: 'Dialog Title 1'});
    diag.dialog('open');
});

Demo



来源:https://stackoverflow.com/questions/4357506/jquery-ui-modal-dialog-better-way-to-create-content-of-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!