首页 > 解决方案 > 将错误消息与图标动态绑定到单个 jQuery 对话框

问题描述

我创建了一个全局 jQuery 对话框来显示应用程序中的所有错误消息。我可以将错误消息绑定到对话框,但是我无法同时显示该图标。为简单起见,我提供了一个带有通用 google 图像的示例。

任何线索将不胜感激,或者如果有更好的方法,请提及。提前致谢

function showAlertDialog(message) {
            var $dialog = $('#ErrorMessageDialog')
                   .html(message)
                   .dialog({
                       modal: true,
                       title: 'Data Error!',
                       width: 400,
                       buttons: {
                           Ok: function () {
                               $(this).dialog('close');
                           }
                       }
                       
                   });
            $dialog.dialog('open');
        }
        
        $("#btnOk").click(function(){
        showAlertDialog('Ok is clicked');
        });
        
        $("#btnCancel").click(function(){
        showAlertDialog('Cancel is clicked');
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<div id="ErrorMessageDialog" style="display:none;">
        <table>
            <tr>
                <td><img src="https://www.google.co.in/logos/doodles/2014/world-cup-2014-1-6584893165273088-res.png"/></td>/*display icon*/
                <td></td>/*display error message*/
            </tr>
        </table>
    </div>

<input type="button" id="btnOk" value="OK"/>
<input type="button" id="btnCancel" value="Cancel"/>

标签: javascriptjqueryjquery-uidialog

解决方案


您必须选择要更新的特定表格单元格。考虑使用类选择器。

例子

$(function() {
  function showAlertDialog(ttl, msg) {
    var $dialog = $('#ErrorMessageDialog')
      .dialog({
        modal: true,
        title: ttl,
        width: 400,
        buttons: {
          Ok: function() {
            $(this).dialog('close').dialog("destroy");
          }
        }
      });
    $('.message', $dialog).html(msg);
    $dialog.dialog('open');
  }

  $("#btnOk").click(function() {
    showAlertDialog('Alert!', 'Ok is clicked');
  });

  $("#btnCancel").click(function() {
    showAlertDialog('Alert!', 'Cancel is clicked');
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<input type="button" id="btnOk" value="OK" />
<input type="button" id="btnCancel" value="Cancel" />

<div id="ErrorMessageDialog" style="display:none;">
  <table>
    <tr>
      <td class="icon"><img src="https://www.google.co.in/logos/doodles/2014/world-cup-2014-1-6584893165273088-res.png" /></td>
      <td class="message"></td>
    </tr>
  </table>
</div>

希望有帮助。


推荐阅读