【问题标题】:ajax generated html being ignored in jquery [duplicate]ajax生成的html在jquery中被忽略[重复]
【发布时间】:2013-11-19 15:59:52
【问题描述】:

当用户登录成功后,它会输出下面的按钮 html

<button class="logout-button">Logout</button>

我也有那个按钮 html 硬编码到 html 中,因为它需要在整个网站的网站上,ajax 仅在成功时输出它,一旦你刷新页面,ajax html 就会消失,我希望这是有道理的。

成功登录后,显示ajax生成的按钮html(如上图)。我单击它,它什么也不做,但如果我刷新页面,它看起来完全一样,因为它现在显示的是硬编码按钮 html(我之前提到过)。当我单击它时,它会按预期将它们注销。我将按钮设置为有一个类而不是 id,因为按钮被硬编码到 html 和显示它的 ajax 中,它可能显示两次,但它没有,但我只是这样做是为了缩小它不有两个具有相同 id 的元素。

下面等待注销按钮被点击,它只在我点击硬编码按钮html时有效,而不是ajax在成功登录时生成的html按钮。

$(".logout-button").click(function(event) 
{
    // stop the contact form from submitting normally
    event.preventDefault(); 

    $.ajax(
    {
        url: "/?ACT=79&return=%2F",
        type: "post",
        dataType: "html",           
        data: $(this).serialize(),

        // there was an error
        error: function(jqXHR, textStatus, errorThrown)
        {
            displayAjaxMessage("Sorry, there was an error logging out, please try again.");
        },

        success: function(html, textStatus, jqXHR) 
        {
            $("#login-form").show();
            $(".logout-button").hide();
            displayAjaxMessage("<p>You are now logged out</p>");
        }

    });
});

下面,登录成功后,生成按钮html:

displayAjaxMessage('<button class="logout-button">Logout</button>');

这里是 displayAjaxMessage,这是 amy h

function displayAjaxMessage(message)
{
    $("#login-form-message").html(message);
    $("#login-form-message").show();
}

硬编码的html是:

<button class="logout-button">Logout</button>

另外,我尝试将按钮点击更改为 $(".logout-button").on('click', function(event) 仍然没有运气。

【问题讨论】:

  • 将 $(".logout-button").click(function(event) 改为 $(document).on('click','.logout-button',function(event)跨度>

标签: javascript jquery html ajax


【解决方案1】:

事件委托!

$("#login-form-message").on("click", ".logout-button", function() {

【讨论】:

    【解决方案2】:

    更改在文档级别附加单击事件以侦听它

    $(".logout-button").click(function(event) {});
    

    $(document).on("click",".logout-button",function(event) {});
    

    【讨论】:

    • 这个答案应该有效。问题是在生成按钮 HTML 之前调用了 onclick 处理程序,因此 onclick 找不到要附加的任何内容。事件委托通过将 onclick 处理程序应用于创建的任何新元素来解决此问题。更多信息:api.jquery.com/on/#direct-and-delegated-events
    【解决方案3】:

    试试这个代码并替换成你的代码

    $(document).on("click",".logout-button",function(event) {});
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2014-10-16
      • 2011-02-07
      • 1970-01-01
      相关资源
      最近更新 更多