【问题标题】:Javascript binding on 'click' and preventDefault() not working'click' 和 preventDefault() 上的 Javascript 绑定不起作用
【发布时间】: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 应该出现在您的 removeFavaddFav 函数的顶部。
  • 就像 Vigneswaran 所说,你不应该为多个元素使用相同的 id,即使你有多个具有相同 id 的元素,你的 $('a#fav').each() 也将始终返回 1 个元素。如果你想为所有元素绑定一些处理程序,给你的a元素,像link这样的类,并使用$('.link').each()来附加处理程序。
  • 同样在你的removeFav()中,在AJAX调用的成功回调中,应该是$(this)而不是$('this')——this周围没有引号

标签: javascript jquery


【解决方案1】:

您需要做的是在事件本身上调用 preventDefault() 方法。要获取事件,您需要将事件传递给您的处理程序 - 事件绑定已经自动完成。

所以你需要做的就是在你的处理程序中使用这个事件。

function removeFav(e) {
    e.preventDefault()
    ...
}

【讨论】:

  • 那行得通。它破坏了我的代码,因为 e.preventDefault() 在 ajax 成功回调中更改了 $(this),所以我的元素没有得到更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多