Flo*_*stv 1 javascript php ajax jquery
我在Laravel中使用AJAX创建了按钮.当我点击跟随时,它会随着id的变化而变成unfollow.我试图再次点击取消关注按钮,它没有在点击功能上执行取消关注,但保留了之前的点击功能.
HTML
<a id="followAnchor" type="submit" class="btn btn-info" /><i class="fa icon-user-follow"></i> Follow</a>
</div>
Run Code Online (Sandbox Code Playgroud)
AJAX
$('#followAnchor').on("click", function(e){
var followId = document.getElementById('followAnchor');
$.ajax({
url: "{{ URL::route('follow-post') }}",
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
}).done(function(response) {
if(response.errors)
{
}
else if (response.success){
followId.innerHTML = "<i class='fa icon-user-follow'></i>" + "Unfollow";
document.getElementById('followAnchor').id = 'unfollowAnchor';
}
});
}
$('#unfollowAnchor').on("click", function(e){
var unfollowId = document.getElementById('unfollowAnchor');
$.ajax({
url: "{{ URL::route('unfollow-post') }}",
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
}).done(function(response) {
if(response.errors)
{
}
else if (response.success){
unfollowId.innerHTML = "<i class='fa icon-user-follow'></i>" + "Follow";
document.getElementById('unfollowAnchor').id = 'followAnchor';
}
});
});
Run Code Online (Sandbox Code Playgroud)
更改后,事件不会神奇地受到约束.代码运行后,它不会继续检查新元素.
冒泡的例子:
$(document).on("click", "#followAnchor", function(e){ /* code here */ });
$(document).on("click", "#unfollowAnchor", function(e){ /* code here */ });
Run Code Online (Sandbox Code Playgroud)