【问题标题】:Rails jquery only loaded to first elementRails jquery 仅加载到第一个元素
【发布时间】:2013-02-15 04:30:22
【问题描述】:

我想创建一个下拉菜单,其中包含指向不同控制器操作的链接。我有一个辅助方法来为我的下拉菜单提供选项。

   def my_product_options(product)
    if product.status == Product::STATUS_INCOMPLETE
       my_options =  {"Select" => '', "Edit info" => edit_product_path(product)}
    elsif product.status == Product::STATUS_ACTIVE
       my_options =  {"Select" => '', "Edit info" => edit_product_path(product), "Suspend" => suspend_product_path(product)}
    end
    my_options
   end

我遍历每个产品并获取每个产品的选项。但问题是所有产品的下拉菜单都加载了他们的选项,但点击仅适用于第一个产品。当我单击其余的下拉选项时,没有任何反应。

我有 jquery 来处理视图中的点击事件

<script>
$('#create_options').change(function() {
    window.location = $(this).find('option:selected').val();
});
</script>

任何建议或解决方案或不同的方法都会有很大帮助。谢谢。

【问题讨论】:

  • 你能发布这个选择列表呈现的 html 是什么样的吗?
  • 所有这些看起来都一样,但产品 ID 不同

标签: jquery ruby-on-rails ruby drop-down-menu


【解决方案1】:

是的,当您在同一个文档上使用 same ids for multiple elements 时会发生这种情况。 You have to use class 代替。

$('.create_options').change(function() {
 //^-----use class instead of id
    window.location = $(this).find('option:selected').val();
});

见:http://jsfiddle.net/X5583/

In fiddle you can see both "using ids" and "using class" try commenting out each
one by one.

如果您对同一页面中的多个元素使用相同的 id 表示法,则只有第一个事件会得到事件,其他事件不会。

【讨论】:

  • &lt;select id="create_options" name="create_options"&gt; - id(和名称)“create_options”需要为每个选择列表更改。你可以像这样添加一个类:&lt;select id="create_options_315" name="create_options_315" class="create_options"&gt;
  • 刚刚添加了一个小提琴。很高兴对您有所帮助。:)
猜你喜欢
  • 2016-11-03
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2013-01-11
  • 2011-08-25
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多