【问题标题】:How to check if an event target value exist in array如何检查数组中是否存在事件目标值
【发布时间】:2018-07-27 10:03:24
【问题描述】:

在我的 rails 应用程序中,我想使用 Jquery 检查来自选择下拉列表的事件目标值是否存在于数组中。如果是这样,我会隐藏一个 div,反之亦然。 在我的控制器中,我派生了数组

def new
  @number = Course.where(course_type: "physical")
  @new_number = @number.ids
end

在我看来,我有这个 jquery 代码

<script>
 var number = <%= @new_number %>;
 document.addEventListener('DOMContentLoaded',function() {
    document.querySelector('select[name="lesson[course_id]"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
    code = event.target.value;
    if($.inArray(code,number) >= 0) {
      $(".vimeo").hide();
    }
    else {
        $(".vimeo").show();
    }
}

</script>

我想检查事件目标值是否包含在“数字数组”中。如果是,我想隐藏 div,反之亦然。

【问题讨论】:

  • 变量number是一个数组吗?
  • 试试if (number.includes(code)) {...} else {...}。还有@courses_ids 或类似的东西,而不是@new_number@number.ids 更清楚(code => selectedCourseId 也)
  • @Satpal yhh,数字是一个数组
  • 感谢@Leo 的建议。我会更改变量名称。但与此同时,该解决方案不起作用
  • 分享console.log(number)console.log(typeof number)的输出

标签: javascript jquery ruby-on-rails ruby ajax


【解决方案1】:
<script>
  var courcesIds = <%= @new_number %>;
  $('select[name="lesson[course_id]"]').change(function(){
    if (courcesIds.includes(parseInt($(this).val()))) {
      $(".vimeo").css("display", "none");
      // $(".vimeo").hide();
    }
    else {
      $(".vimeo").css("display", "block");
      // $(".vimeo").show();
    }
  })
<script>

【讨论】:

  • 它不起作用。当我输入console.log(typeof courseIds)时,它说它是一个对象而不是一个数组。我对此有点困惑
  • @HakeemBaba,typeof [1, 2, 3] #=&gt; 'object'。这是正常的。当想要检查它是否是一个数组时使用Array.isArray(courcesIds) 。有什么错误吗?您能否提供代码 sn-p 的上下文(带有 .vimeo 块)?
  • 这是 vimeo 块代码
  • 我通过 html 渲染它。这是选择代码
  • f.association generate select 包括所有带有字符串值的选项。所以,[int, int, int].includes(string) 总是false
猜你喜欢
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多