javascript - 如何仅为非隐藏媒体查询类触发 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
});
我如何实现这一目标?
解决方案
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">
推荐阅读
- twincat - 为什么存储在单独的 tmc 文件中的事件会重新出现在我的 twincat .tsproj 文件中?
- css - 使用 react-full-page 时页脚未在底部对齐
- mysql - Mysql - 内部连接或条件需要很长时间 mysql
- r - 将JSON读入R中的数据框
- aem - 在多个位置更改多个 AEM 页面中的文本
- powershell - 使用 PowerShell 上传多部分/表单数据文件
- performance - BizTalk 延迟形状是否占用任何资源或对性能不利?
- javascript - 在 JavaScript 中获取两个 URL(在点击监听器内)
- reactjs - 使用 React Navigation 导航到深度嵌套的屏幕
- rust - “找到结构 `ThereIsNoIteratorInRepetition`” 尝试使用 `quote!` 重复向量时