【问题标题】:create dynamically buttons to show dialog创建动态按钮以显示对话框
【发布时间】:2016-04-21 17:47:26
【问题描述】:

我有一个按钮(创建),当它被单击时,它会创建一个新按钮(更改坐标),当它被单击时应该能够打开对话框。

首先我创建了对话窗口的主体,我通过 JavaScript 创建了它,这就是它在 HTML 中的样子:

<div id="dialog-form" title="Change coordinates">
  <p class="validateTips">Both fields are required.</p>
  <form>
    <fieldset>
    <label for="lon">Longitude (decimal)</label>
    <input type="text" name="lon" id="lon" value="" class="text ui-widget-content ui-corner-all">
    <label for="lat">Latitude (decimal)</label>
    <input type="text" name="lat" id="lat" value="" class="text ui-widget-content ui-corner-all">

    <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
  </form>
</div>

现在当点击创建按钮时,我会创建一个能够打开对话框的新按钮:

$( "#create" ).button().on( "click", function()
{
    var btn = document.createElement("BUTTON");
    btn.id = "change_coord";
    var t = document.createTextNode("Change coordinates");
    btn.appendChild(t);
    document.body.appendChild(btn);
});

这就是我的对话框的样子:

dialog = $( "#dialog-form" ).dialog({
          autoOpen: false,
          height: 300,
          width: 350,
          modal: true,
          buttons:{
                "Create an account": addUser,
                Cancel: function(){
                    dialog.dialog( "close" );
                }
          },
          close: function(){
                form[ 0 ].reset();
                allFields.removeClass( "ui-state-error" );
          }
});

奇怪的是,当我创建对话框主体和按钮以在其中打开它时它可以工作

$(function()
{
....
});

但是当我动态创建此按钮以打开对话框时,它根本不起作用。
HERE 是我向您展示我的问题的小提琴。

【问题讨论】:

  • thisthisthis 和许多其他的可能重复。在 Google 上尝试“jquery 动态元素侦听器”。

标签: javascript jquery html jquery-ui dialog


【解决方案1】:

Per Charlietfl,正确的“live”已被弃用,但它仍然是解决问题的常见方法。我使用的另一种方法也有效:

$(document).on("mouseenter","#lsTMFmenu", function() {

但是,我无法让 JQuery 仅使用 $("#selector").on() 来处理动态加载的 HTML,我必须使用上面显示的 $(document).on 语句。

谢谢。

【讨论】:

  • live() has been deprecated 多年了。答案是倒退...应该使用on()
  • 我了解 live 已被弃用,但不会提供所需的功能。我每天都使用它,当我动态生成包含更多 JQuery 的内容时,总是必须恢复为“实时”。另一种选择是使用 $(document).on("click","#selector", function() { *** 但这在具有许多元素的大型 html 页面上效率不高。苛刻。
  • 不推荐使用 live() 并创建 on() 有很好的性能原因。这种变化同时发生在图书馆里。此外,您不必一直进行文档委派。可以使用任何固定资产祖先
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2012-01-30
相关资源
最近更新 更多