如何遍历多个元素并在每个元素上附加点击功能?

How do I loop through multiple elements and attach a click function on each?

我正在尝试遍历 rails 应用中 ruby 中的多个元素,以便根据在 div 中选择的元素显示或隐藏 div下拉菜单(或单选按钮或其他)。

我的 javascript/coffescript 知识匮乏,但经过几天的研究,我有了一个可行的解决方案,尽管它的构造非常糟糕。

$(document).on "turbolinks:load", ->
  if $('select[id="open_closed[1]"]').val() == "0" or $('select[id="open_closed[1]"]').val() == "1"
    $('#open_close_times_1').hide()
  $('select[id="open_closed[1]"]').click ->
    if $('select[id="open_closed[1]"]').val() == "0"
      $('#open_close_times_1').hide()
    if $('select[id="open_closed[1]"]').val() == "1"
      $('#open_close_times_1').hide()
    if $('select[id="open_closed[1]"]').val() == "2"
      $('#open_close_times_1').show()

  if $('select[id="open_closed[2]"]').val() == "0" or $('select[id="open_closed[2]"]').val() == "1"
    $('#open_close_times_2').hide()
  $('select[id="open_closed[2]"]').click ->
    if $('select[id="open_closed[2]"]').val() == "0"
      $('#open_close_times_2').hide()
    if $('select[id="open_closed[2]"]').val() == "1"
      $('#open_close_times_2').hide()
    if $('select[id="open_closed[2]"]').val() == "2"
      $('#open_close_times_2').show()
.
.
.
return

这用于设置商店一周中几天的营业时间,因此以下代码段最多扩展到 open_closed[7]。我确定这应该通过循环来完成,而不是将每个都写出来。我还有一个 "holidays" 的版本,它有任意天数 - 所以这个解决方案在那里完全失败,但循环将是完美的。

我一直在尝试将其提取到某种循环中以达到相同的效果(因此我可以在这里最多执行 7 个代码,而其他代码最多可以执行任意最大值),但我找不到允许我执行此操作的教程或说明。这是我进行黑客攻击的第 4 天,因此非常感谢收到任何指示,我需要做些什么才能将其重构为一个明智的解决方案?

在 jQuery 中,使用不太具体的 selector 获取您要定位的 select 项的数组。例如,您可以使用 selector 开头。然后遍历结果以隐藏元素并添加点击事件。

$(document).on("turbolinks:load", function () {
  var options = $("select[id^='open_closed']");
  $.each(options, function(index, item){
    if ($(item).val() == 0 || $(item).val() == 1) {
      $(item).hide();
    }

    $(item).on("click", function() {
      var open_close_selector = "#open_close_times_" + (index + 1);
      if ($(item).val() == "0" || $(item).val() == "1"){
        $(open_close_selector).hide();
      } else {  
        if ($(item).val() == "2") {
          $(open_close_selector).show();
        }
      }
    });
  });
});

这可以稍微清理一下,但它应该给你一个起点。

好的 - 所以经过一些修改并受到 margo 的回答的启发,这对我有用:

$(document).on 'turbolinks:load', ->
  options = $('select[id^=\'open_closed\']')
  $.each options, (index, item) ->
    open_close_selector = '#open_close_times_' + index
    if $(item).val() == '0' or $(item).val() == '1'
      $(open_close_selector).hide()
    $(item).click ->
      if $(item).val() == '0' or $(item).val() == '1'
        $(open_close_selector).hide()
      else
        if $(item).val() == '2'
          $(open_close_selector).show()
      return
    return
  return