Jquery 仅创建第一个动态生成的选择框

Jquery 仅创建第一个动态生成的选择框,jquery,css,ruby-on-rails,ruby-on-rails-3,Jquery,Css,Ruby On Rails,Ruby On Rails 3,我认为有以下代码: <% @games.each_with_index do |game, i| %> <div class="game_<%= i %> game_hide hide" > <% options = options_from_collection_for_select(Player.where("game_id = ?", game.id), 'id', 'handle' ) %> <%= f.selec

我认为有以下代码:

<% @games.each_with_index do |game, i| %>
  <div class="game_<%= i %> game_hide hide" >
    <% options = options_from_collection_for_select(Player.where("game_id = ?", game.id), 'id', 'handle' ) %>
    <%= f.select(:player_ids, options, {:include_blank => true}, {id: "game_#{i}", :multiple => true} ) %>
  </div>
<% end %>

一切都“在那里”-我可以在Chrome的开发者工具页面上找到它,但选择框只在第一个游戏(
game\u 0
)中显示-因此,我认为
id
存在某种问题,但我不知道它是什么

首先,jQUERY中有一个错误。隐藏
div
,但试图显示
select
元素。将其更改为:

//if this thing happens
//hides all game divs
$(".game-hide").hide();
//shows the game div for the selected game with good index method
$(".game-"+ $('.show-tabs .show-tab').index($(this))).parent('.game-hide').show();
说明:


$(this)
$('.show tabs.show tab').live('click'
)相关。这是您单击的当前选项卡。因此,要检索
$(this)
的索引,您必须与所有
$('.show tabs.show tab')
元素进行比较。更多解释我认为这是因为使用了下划线()在id和类中。这是我发现的。可能有一些用处


问题似乎出在
.index()
方法的使用上。如果在没有任何参数的情况下调用该方法,那么它将返回一个整数,即基于兄弟元素的元素位置。因此,在这种情况下,
$(this).index()
返回0。因此,我建议使用同一方法的不同变体

更换这条线

$(".game-"+ $(this).index()).show();


现在,它将根据与
$('.show tabs.show tab')
选择器匹配的所有元素返回当前元素的索引或位置。

我认为您关于
.game\u hide
div的说法是正确的,但它工作不正常。感谢您的回答。我已经更新了我的答案,以说明
.index()
有效。(不正确,因为我不知道
$(这个)
是什么!对不起…可能我只是傻了,但是
所有这些元素的选择器应该是什么呢?
游戏隐藏的父项
/
游戏x
?我试过了(它是
添加玩家
),但在你的情况下没有得到任何结果,它将是
$('.show tabs.show tab')
。请看我的帖子,我已经更改了它!但没有这样做。我感谢您的帮助,如果我不知道它的历史,我会给您另一个+1。谢谢!问题是
index()
方法。
$(this.index())
将始终返回0。如果您能告诉我您要将此代码添加到的事件是什么,那么我可以在代码级别上帮助您。:)我会更新我的帖子,但您所说的不是真的;)
警报($(this).index());
返回
0
1
2
,具体取决于我选中的框,请尝试
$('.show tabs.show tab')。索引($(this))
$(“.game-”+$('.show tabs.show tab')。索引($(this)))。show();
代替了
$(“.game-”+$(this.index())。show();
。请注意,
$(“.game-”
中有
(下划线)在code.ah right中,我在阅读Sandeep Nayak的答案后在代码中添加了
-
,但没有在问题中更改它们,我的错。让我试试这个!
//if this thing happens
//hides all game divs
$(".game-hide").hide();
//shows the game div for the selected game with good index method
$(".game-"+ $('.show-tabs .show-tab').index($(this))).parent('.game-hide').show();
$(".game-"+ $(this).index()).show();
$(".game-"+ $('.show-tabs .show-tab').index($(this))).show();