【发布时间】:2015-07-13 11:44:24
【问题描述】:
对 JavaScript 相当陌生。当页面加载时,它将removeFav/addFav函数绑定到anchor标签的点击事件。一切都按预期工作,但是当用户单击链接时,它会将用户带到页面顶部。我在每个函数的不同位置尝试了 preventDefault() 。它会停止默认点击,但会阻止其余代码运行或破坏功能。
preventDefault() 仍然是正确的方法吗? preventDefault() 应该去哪里?每次单击链接时,如何阻止页面返回顶部。任何帮助将不胜感激。
JavaScript 代码:
// Add a favorite
function addFav() {
var id = $(this).data('id');
var url = '/listings/' + id + '/favorite';
$.ajax({
url: url,
type: 'put',
success: function(){
$('this')
.addClass('active')
.off('click')
.on('click', removeFav)
;
console.log("success in add function");
},
error: function() {
console.log("error in add function");
}
});
}
// Remove a favorite
function removeFav() {
var id = $(this).data('id');
var url = '/listings/' + id + '/unfavorite';
$.ajax({
url: url,
type: "post",
dataType: "json",
data: {"_method":"delete"},
success: function(){
$('this')
.removeClass('active')
.off('click')
.on('click', addFav)
;
console.log("success in remove function")
},
error: function() {
console.log("error in remove function")
}
});
}
// Attach the add or remove event handler to favorite links
function attachFavHandler() {
$('a#fav').each( function() {
var status = $(this).hasClass('active');
if (status) {
$(this).on('click', removeFav);
} else {
$(this).on('click', addFav);
}
console.log(status)
});
}
// Lets get the 'favorites' party started
attachFavHandler();
Rails 代码:
<% if user_signed_in? %>
<% if current_user.favorites.where(:listing_id => listing.id).first.nil? %>
<%= link_to "", "", :id => "fav", :class => "", :'data-id' => "#{listing.id}" %>
<% else %>
<%= link_to "", "", :id => "fav", :class => "active", :'data-id' => "#{listing.id}" %>
<% end %>
<% end %>
【问题讨论】:
-
为什么要给每个锚元素相同的 ID ?
-
preventDefault应该出现在您的removeFav和addFav函数的顶部。 -
就像 Vigneswaran 所说,你不应该为多个元素使用相同的 id,即使你有多个具有相同 id 的元素,你的
$('a#fav').each()也将始终返回 1 个元素。如果你想为所有元素绑定一些处理程序,给你的a元素,像link这样的类,并使用$('.link').each()来附加处理程序。 -
同样在你的
removeFav()中,在AJAX调用的成功回调中,应该是$(this)而不是$('this')——this周围没有引号
标签: javascript jquery