更新 ID 和 jQuery 事件处理程序时出现问题 [关闭]

问题描述 投票:0回答:1

我正在尝试制作某种形式,但我无法进入第 3 步。

我的下一个按钮确实有一个像这样的递增 ID:

$('#to-q-2').click(function (e) {
    e.preventDefault();
    $(this).attr("id", "to-q-3");
})

所以id更新了。 但是当我再次点击时:

$('#to-q-3').click(function(e) {
        e.preventDefault();
        alert('stop');
});

什么都没发生。我猜 jQuery 没有更新 DOM,但我不知道该怎么做。有什么线索吗?

javascript jquery forms jquery-selectors
1个回答
2
投票

您需要将点击事件添加到

document
,以便它可以查找在
click
事件的初始绑定时不存在的新元素,这样您就可以将点击事件添加到动态添加的元素。您可以使用:

$(document).on('click', '#to-q-3', function() {...})

参见下面的工作示例:

$(document).on('click', '#to-q-2', function (e) {
    e.preventDefault();
    $(this).attr("id", "to-q-3");
});

$(document).on('click', '#to-q-3', function(e) {
  e.preventDefault();
  alert("stop");
});
#to-q-2 {
  color: red;
}

#to-q-3 {
  color: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="to-q-2">Click this div</div>

© www.soinside.com 2019 - 2024. All rights reserved.