我正在为我的应用程序中的个人资料开发 +Follow 功能。跟随功能只能工作一次(在新页面加载时),但在脚本替换 DOM 元素后,它就不起作用了。
用户未关注配置文件时的 HTML 输出:
<div id="follow">
<a>Follow profile</a>
</div>
HTML 输出 当用户当前关注个人资料时:
<div id="unfollow">
<a>Unfollow profile</a>
</div>
神奇的事情发生在 jQuery 中。以下函数包装在 $(document).ready()
函数中:
function follow() {
$("#follow a").on("click", function() {
// $.getJSON fn here that follows profile and returns success T/F
if ( success ) {
$("#follow").remove();
$("#follow-container").html('<div id="unfollow"><a>Unfollow profile</a></div>');
}
});
$("#unfollow a").on("click", function() {
// $.getJSON fn here that unfollows profile and returns success T/F
if ( success ) {
$("#unfollow").remove();
$("#follow-container").html('<div id="follow"><a>Follow profile</a></div>');
}
});
}
假设用户单击“关注个人资料”。该脚本删除了#follow a
链接,并将其替换为#unfollow a
链接。但是,单击 #unfollow a
时运行的 JS 脚本不会执行,因为该元素是在页面加载后添加到 DOM 中的。
为了解决这个问题,我尝试像这样刷新函数:
if ( success ) {
$("#follow").remove();
$("#follow-container").html('<div id="unfollow"><a>Unfollow profile</a></div>');
// reload function
follow();
}
这行不通。未注册取消关注点击事件。在这种情况下我该如何重新加载 DOM?
最佳答案
使用事件委托(delegate) -
$("#follow-container").on("click","#follow a", function() {
和
$("#follow-container").on("click","#unfollow a", function() {
另外:这里有一个拼写错误 $(#follow-container")
这应该是 $("#follow-container")
关于javascript - 添加新元素到 DOM 后如何重新加载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16649959/