首页 > 解决方案 > 选择 .each() 函数在其上运行的元素

问题描述

我有这段代码,但elem没有定义。也尝试过this$(this)但得到了文件。

我应该提到 $('.listop') 是一个 jquery 对象数组(这就是我使用每个对象的原因)。在每个 listop 元素之前,它们是一个 radioOption 元素,我需要对它们每个元素,当一个人单击“listop”时,将检查“radioOption”。

let inputs = $('.listop');
$(document).ready(function() {
  inputs.each(function(int, elem) {
    elem.click(function() {
      elem.closest('.radioOption').prop('checked', true);
    });
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
  <td>
    <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
  <td> לנמען יחיד</td>
  <td>
    <div id="lonly" class="listop" style="display: inline;">
<input type="text" name="mobile">

标签: jquery

解决方案


我假设你的意思是这个

  1. 查找输入的 tr 父级
  2. 在该行中找到具有类 .radioOption 的复选框并检查它

注意,事件处理程序将对所有 .listop 输入起作用,并且仅选中同一行中的复选框

$(function() {
  $(".listop input").on("click",function() {
      $(this).closest("tr").find('.radioOption').prop('checked', true);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
    <td> לנמען יחיד</td>
    <td>
      <div id="lonly" class="listop" style="display: inline;">
        Mobile: <input type="text" name="mobile">
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
    <td> לנמען יחיד</td>
    <td>
      <div id="lonly" class="listop" style="display: inline;">
        Mobile: <input type="text" name="mobile">
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
    <td> לנמען יחיד</td>
    <td>
      <div id="lonly" class="listop" style="display: inline;">
        Mobile: <input type="text" name="mobile">
      </div>
    </td>
  </tr>
</table>


推荐阅读