【发布时间】:2014-10-03 07:12:45
【问题描述】:
我正在为系统中的不同成员创建关注/取消关注按钮。在按钮所在的同一个 div 中再次呈现 html 后,我遇到了 jQuery 事件没有被触发的问题。关注/取消关注按钮第一次工作 - 总是,但永远不会第二次尝试。其他依赖于javascript的东西仍然有效,所以它也不是js中的错误。
//html snippet
<div id="start-members">
<div class="content">
<div class="result">
<div class="items-column member"><div class="image-holder">
<img src="imagefile"></div>
<span class="button-section">
<a href="#" data-userid="61" class="follow button trans-effect follow-user"><span class="following-text">Follow</span><span class="unfollow-text">Unfollow</span></a>
</span>
<div class="clearfix"></div></div>
<div class="items-column member"><div class="image-holder">
<img src="imagefile"></div>
<span class="button-section">
<a href="#" data-userid="95" class="follow button trans-effect follow-user"><span class="following-text">Follow</span><span class="unfollow-text">Unfollow</span></a>
</span>
<div class="clearfix"></div></div>
<div class="items-column member"><div class="image-holder">
<img src="imagefile"></div>
<span class="button-section">
<a href="#" data-userid="104" class="follow button trans-effect follow-user"><span class="following-text">Follow</span><span class="unfollow-text">Unfollow</span></a>
</span>
<div class="clearfix"></div></div>
</div>
</div>
</div>
//jQuery
//This returns html and put it into result-div above
function getLatestMembers() {
var getLatest = $.ajax({
type: 'GET',
url: '/index.php/members/getlatest',
dataType: 'json'
});
//If success, returning html
getLatest.done(function(data) {
$("#start-members .result").html(data);
});
getLatest.fail(function(ts) {
alert(ts.responseText);
});
}
//Toggle between following this user or not
$(".content .button-section").on('click', '.button.follow-user', function(e) {
e.preventDefault();
//doing toggle of the button (to unfollow-user/follow-user)
getLatestMembers(); //When having this call it renders the div latest members and next time this event is not fired. why?
});
//Unfollow user that has created this outfit
$(".content .button-section").on('click', '.button.unfollow-user', function(e) {
e.preventDefault();
//doing toggle of the button (to unfollow-user/follow-user)
getLatestMembers(); //When having this call it renders the div latest members and next time this event is not fired. why?
});
我也试过在事件调用中只使用getLatestMembers()。下次不触发该事件。
//Unfollow user that has created this outfit - fired only once
$(".content .button-section").on('click', '.button.unfollow-user', function(e) {
e.preventDefault();
getLatestMembers();
});
我希望我已经描述了这个场景,以便你们理解我的问题/问题:-)(问题是:为什么事件没有触发一次以上?)
【问题讨论】:
-
你正在替换 getLatestMembers() 中的按钮
-
你能不能把代码的那些事件绑定部分放到一个单独的函数中,并且每次都在 getLatest.done 中调用那个函数