首页 > 解决方案 > 如何仅为非隐藏媒体查询类触发 JS 事件?

问题描述

对于移动和桌面(媒体查询),我几乎没有具有相同类名的输入 html 标签

有时$(".className").val()是空的,因为它从隐藏的 html 标记中获取值。

$(".className").val() 应该只从非隐藏的 html 标记中获取值。

html -

  <div class="mobileDiv">
    <input type="text" class="searchItem">
    <input type="text" class="searchCategory">
  </div>

  <div class="desktopDiv">
    <input type="text" class="searchItem">
    <input type="text" class="searchCategory">
  </div>

Javascript -

// Same code is shared for both mobile and desktop

$(document).on('keyup', '.searchItem', function() {
  val = $(".searchItem").val() 
  categoryVal = $(".searchCategory")

  // cannot use "this" because other class values are also needed on this event
});

我如何实现这一目标?

标签: javascriptjqueryresponsive-designevent-handlingdom-events

解决方案


Using$(".searchItem").val()将始终返回在页面中找到的第一个值。

在事件处理函数this中是事件实际发生的元素

$(document).on('keyup', '.searchItem', function() {
  let val = $(this).val() 
  console.log(val)
});
input.mobileDiv{display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="searchItem mobileDiv">

<input type="text" class="searchItem desktopDiv">


推荐阅读