对于 JavaScript 来说还很陌生。当页面加载时,它将removeFav/addFav函数绑定(bind)到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();
轨道代码:
<% 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 %>
最佳答案
您需要做的是调用事件本身的 PreventDefault() 方法。要获取事件,您需要将事件传递给处理程序 - 事件绑定(bind)已经自动执行此操作。
因此,您所需要做的就是在处理程序中使用此事件。
function removeFav(e) {
e.preventDefault()
...
}
关于Javascript 绑定(bind) 'click' 和 PreventDefault() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30024207/