使用AJAX加载元素时重新加载JS函数
$('#followUser').click(function () { var userId = $(this).attr('data-userId'), action = $(this).attr('data-action'), currentUser = $(this).attr('data-currentUserId'), elem = $(this); $.ajax({ method: 'POST', url: "/sci-profile/profile/follow", data: { userId: currentUser, profileUserId: userId, action: action }, success: function(response) { elem.parent().load(window.location.href + ' #unFollowUser'); } }); });
点击按钮后,JS加载了包含其所有内容的新div,这很好,但是在加载新div时会出现问题。
JS无法识别新ID
。 当我点击新按钮时没有任何反应,因为当新元素不存在时,JS函数已加载。
有没有办法让一些监听器检查新DIV
加载,然后加载对应于该元素ID
JS函数?
你应该使用委托
例如,你有这个标记
.....some content here....
- #contentWrapper – 静态块
- 里面的任何东西 – 动态内容
现在你应该绑定你的事件
$('#contentWrapper').on('click', '#followUser' 'function () { ...code here... });
是的,我做到了。
这是HTML
{% if followsId == null %} Follow {% else %} Unfollow {% endif %}
还有JS代码
$('.follow').delegate('div', 'click', function(){ action = $(this).attr('data-action'); elem = $(this); if (action == 'follow'){ var userId = $(this).attr('data-userId'), currentUser = $(this).attr('data-currentUserId'); $.ajax({ method: 'POST', url: "/sci-profile/profile/follow", data: { userId: currentUser, profileUserId: userId, action: action }, success: function(response) { elem.parent().load(window.location.href + ' #unFollowUser'); } }); } if (action == 'unFollow'){ var followsId = $(this).attr('data-followsId'); $.ajax({ method: 'DELETE', url: "/sci-profile/profile/unFollow", data: { followsId: followsId }, success: function(response) { elem.parent().load(window.location.href + ' #followUser'); } }); } });
我希望这会对某人有所帮助。