创建自定义 jQuery UI 关闭按钮

Create custom jQuery UI close button

这里有几个关于这个问题或类似问题的回复 - 它们要么已过时,要么不准确。

我正在尝试将我自己的自定义关闭元素添加到 jQuery UI 对话框中。 我猜我需要使用委托处理程序或能够响应对话框函数触发的某些事件。

显然 $(document).ready() 不会工作,因为对话框发生在文档加载之后。

所以 - 怎么办?我确定我遗漏了一些非常简单的东西。 (希望) 参考:https://api.jqueryui.com/dialog

到目前为止,我得到的反馈假设有一个元素我可以在其上附加事件处理程序...它在脚本 运行 中的页面时不存在问题

当且仅当我从调试 window 中 运行 它并打开对话框时才有效。当我把这个简单的命令放在附加到页面的脚本中时......没有任何附加内容 我在这个例子中使用的命令非常非常简单

jQuery( ".name-group-name" ).click(function() {
  console.log('hello');
});

还不清楚你想要什么,你也没有提供例子。这是来自 https://jqueryui.com/dialog/

的基本对话框示例

首先我们初始化对话框。完成后,我们可以使用 widget method 来处理包装器。我们可以 select 小部件中的特定元素,然后根据需要更改它。

$(function() {
  var dlg = $("#dialog").dialog();
  var dlgClose = dlg.dialog("widget").find(".ui-dialog-titlebar-close");
  console.log(dlgClose);
  var newButton = $("<button>", {
    class: "ui-dialog-titlebar-close"
  }).html("Close").button().click(function() {
    dlg.dialog("close");
  });
  dlgClose.replaceWith(newButton);
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

如果您只想更改图标,可以找到 <span> 并删除当前的 ui-icon-closethick class 并添加您自己的图标。如果你想替换元素,你可能需要绑定一个新的 click 事件到它。

现在可以看到元素是:

<button class="ui-dialog-titlebar-close ui-button ui-corner-all ui-widget">Close</button>

希望对您有所帮助。

找到解决方案。 回顾一下,我正在执行一个如下所示的命令:

<a href="/admin/config/development/sync/diff/block.block.bartik.search" class="use-ajax" data-accepts="application/vnd.drupal-modal">Show me a modal</a>

(部分)解释了其工作原理的逻辑和机制 here

问题是每个示例和建议都假设 jQuery Dialog 元素是用我的代码显式创建的。事实并非如此。 None 提供的解决方案将在没有以下内容的情况下工作。

不知何故,我们必须监听这个事件。这样做是这样的:

// catch dialog event
$(document).on("dialogopen", ".ui-dialog", function (event, ui) {
    //Do some work here
});

非常接近 jQuery API 参考中的代码示例:

$( ".selector" ).on( "dialogopen", function( event, ui ) {} );

不同之处在于事件未绑定到 non-existent 选择器(这正是我试图解释的问题。相反,它绑定到 $(document)。

希望这会让其他人避免几天的反复试验