0

我有一个用户页面,用户在其中列出了他的关注者和他关注的用户。如果他点击一个按钮,它会显示关注者。如果他点击另一个按钮,它会显示他关注的用户。

我不明白 jquery 事件第二次而不是第一次触发。我在 show.html.erb 中设置了用户“关注”列表。这是匹配的 show.js.erb:

$(function(){
    $("#trusts_list_button").click(function(){
        $("#relationship_list").html("<%= escape_javascript(render 'follows') %>");
    });
    $("#trusted_list_button").click(function(){
        $("#relationship_list").html("<%= escape_javascript(render 'followers') %>");
    });
});

这是展示视图:

<%= @user.name %>
<%= link_to "Add friends", facebook_friends_user_path %>

<table><tr><td>
<%= link_to "Trusts", "#follows", :id => "trusts_list_button", :remote => true%></td>
<td><%= link_to "Trusted by", "#followers" , :id => "trusted_list_button", :remote => true %></td></tr></table>
<div id = "relationship_list"><%= render 'follows' %></div>

第一次单击后,两个按钮都可以正常工作。但是第一次初步点击真的让我失望。如果有任何帮助,我将不胜感激;这不是我第一次遇到 JQuery 问题,而且对于解决这种简单的问题我真的很茫然。

4

3 回答 3

0

作为一个快速修复试试这个:

$(function(){
    $("#trusts_list_button").click(function(){
        $("#relationship_list").html("<%= escape_javascript(render 'follows') %>");
    }).click();
    $("#trusted_list_button").click(function(){
        $("#relationship_list").html("<%= escape_javascript(render 'followers') %>");
    }).click();
});

发生时doc ready,它第一次点击。

于 2013-03-04T07:35:29.713 回答
0

第一件事.. ID 应该始终是唯一的.. 你有两个具有相同 id 的元素.. 所以 chnage

...
<%= link_to "Trusts", "#follows", :id => "trusts_list_follows_button", :remote => true%></td>
<td><%= link_to "Trusted by", "#followers" , :id => "trusted_list_followers_button", :remote => true %>
....

然后为每个按钮调用你的点击事件

$(function(){
  $("#trusts_list_follows_button").click(function(){
    $("#relationship_list").html("<%= escape_javascript(render 'follows') %>");
  });
  $("#trusted_list_followers_button").click(function(){
    $("#relationship_list").html("<%= escape_javascript(render 'followers') %>");
  });
});

您在代码中遇到的问题是,单击事件是针对相同的按钮 .. 因为您的选择器是$("#trusted_list_button"). 这将选择id=trusted_list_button在您的情况下是两个按钮的按钮..因此单击事件仅针对第二个按钮触发...

于 2013-03-04T07:21:52.910 回答
0

我最近遇到了这个问题,我确定克隆元素上存在一个事件 - 但我找不到或删除该事件(虽然我知道它在那里)...单击 1 - 无,单击 2 - 触发通常,单击 3 - 触发两次(有点)

我的解决方案是再次克隆特定的违规元素并使用克隆(这次没有克隆事件)来替换原始元素。

$(el).replaceWith($(el).clone());

于 2014-10-20T16:55:24.937 回答