javascript - 如何使用 jQuery 定位 div 内复选框的值?

标签 javascript html jquery

这是代码-

<div class="filter-box" id="categoryFilter">             
    <input type="checkbox" id="3" name="Education" value="3">
    <label for="Education">Education</label>
    <input type="checkbox" id="12" name="Employment" value="12">
    <label for="Employment">Employment</label>
    <input type="checkbox" id="5" name="Goods and Services" value="5">
    <label for="Goods and Services">Goods and Services</label>
</div>

我需要定位所单击复选框的值或 ID,以便将其添加到 API 调用的 URL 字符串中。

如何定位该复选框,以便编写返回值的点击事件?

最佳答案

  • 标签的 for应匹配id ,而不是输入的 name
  • 不要过度使用数字 ID,有时您的 ID 很可能会重复和冲突。相反,删除 idfor属性并将您的输入包装到 <label>
  • 使用 jQuery 的“change”事件函数回调
  • 使用 .prop() 获得所需的属性值

$("#categoryFilter").on("change", ":checkbox", function() {
  const name = $(this).prop("name");
  const value = $(this).prop("value");
  const checked = $(this).prop("checked");
  console.log(`${name} ${value} ${checked}`);
});
<div class="filter-box" id="categoryFilter">
  <label>
    <input type="checkbox" name="Education" value="3">
    Education
  </label>
  <label>
    <input type="checkbox" name="Employment" value="12">
    Employment
  </label>
  <label>
    <input type="checkbox" name="Goods and Services" value="5">
    Goods and Services
  </label>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

随着 IE 浏览器的消亡,以及长青浏览器与最新的 ECMAScript 保持同步,现在 jQuery 已经不再是必需的了。没有像 jQuery 这样的库的开销的纯 JavaScript 方法是:

document.querySelector("#categoryFilter").addEventListener("change", (evt) => {
  const el = evt.target.closest("[type=checkbox]");
  if ( !el ) return; // Not a checkbox
  console.log(`${el.name} ${el.value} ${el.checked}`);
});
<div class="filter-box" id="categoryFilter">
  <label>
    <input type="checkbox" name="Education" value="3">
    Education
  </label>
  <label>
    <input type="checkbox" name="Employment" value="12">
    Employment
  </label>
  <label>
    <input type="checkbox" name="Goods and Services" value="5">
    Goods and Services
  </label>
</div>

另请注意,上面的纯 JavaScript 示例使用 Event delegation ,类似于您在 jQuery 中使用 $(parent).on("eventName", "dynamicChild", fn) 执行的操作- 即使对于动态创建的复选框元素也适用。

关于javascript - 如何使用 jQuery 定位 div 内复选框的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76150658/

相关文章:

javascript - jQuery 中的按键

javascript - Vue + Jest 模拟全局方法

javascript - 验证电子邮件地址

javascript - 创建一个div,其aspect为16 :9 while having height 100%

javascript - 使用 JavaScript 检查下拉列表的选定选项是否不是第一个

javascript - FullCalendar 按钮放置月份名称应位于左右箭头之间

javascript - javascript d3 和 dc 的概率密度函数

html - 页面在本地看起来不错。但是当推送到服务器时,一切都会放大

jquery 添加类显示 block 和无

jquery - jQgrid行内编辑:-How to give specific edittype to particular jqgrid cell?