2013-03-04 85 views
0

我有一个用户页面,用户列出他的追随者和他关注的用户。如果他点击一个按钮,它会显示追随者。如果他点击另一个按钮,它会显示他的跟随用户。jquery事件只发射第二次点击 - 为什么?

我不明白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问题,而且我对修复这种简单问题感到茫然。

+0

嗨Sudhir ...你是什么意思?每个功能都与不同的项目有关。 – Laurent 2013-03-04 07:15:40

+0

':remote => true'有什么意义? – apneadiving 2013-03-04 07:39:14

+0

@apneadiving我刚刚删除:remote => true并猜测是什么? JQuery完全停止响应。我认为:remote => true恰恰是为了发挥JQuery的作用。 – Laurent 2013-03-04 07:41:43

回答

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而你的情况是这两个按钮按钮..所以click事件被解雇仅仅第二个按钮...

+0

嗨,比尔,谢谢你,但第一个元素是“trusts_list_button”,第二个是“trusted_list_button”。 IT有点混乱,所以我改了名字,但问题仍然存在。也许我误解了你的评论? – Laurent 2013-03-04 07:29:15

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第一次发生点击。

0

我最近遇到了这个问题,我确定克隆的元素上存在一个事件 - 但我找不到或删除事件(虽然我知道它在那里)...点击1 - 没有任何事情,点击2 - 正常点击,点击3 - 点击两次(排序)

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

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

相关问题