单击时更改无线电输入值(实际上将其更改回来)

Change radio input value on click ( change it back actually )

本文关键字:回来 实际上 无线电 输入 单击      更新时间:2023-09-26

单击选择x2div时更改无线电输入选择:

                <div class="row">
                    <div class="box">
                        <div class="inputoptions">
                            <span><input type="radio" name="abc" value="x1" checked="checked" class="y1" /> x1</span>
                            <span><input type="radio" name="abc" value="x2" class="y2" /> x2</span>
                            <span><input type="radio" name="abc" value="x3" class="y3" /> x3</span>
                        </div>
                        <div class="selectx2">select x2</div>
                        <div class="clear"></div>
                    </div>

这是我的JavaScript来更改/选择x2:

$('.selectx2').on('click', function(e) {
    $(this).closest('.box').children('.inputoptions').children('.y2').prop('checked', true);
});

我哪里犯了错误?

当你使用.children()时,它会找到元素的直接子级,y2不是inputoptions的直接子级。

您可以使用.find()

获取当前匹配元素集中每个元素的后代,按选择器、jQuery 对象或元素进行筛选。

    $(this)
     .closest('.box')
     .children('.inputoptions')
     .find('.y2') //Use find here instead of children
     .prop('checked', true);                                                

 $(this)
     .closest('.box')
     .find('.inputoptions .y2')
     .prop('checked', true);

$(document).ready(function() {
  $('.selectx2').on('click', function(e) {
    $(this).closest('.box').find('.inputoptions .y2').prop('checked', true);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="box">
    <div class="inputoptions">
      <span><input type="radio" name="abc" value="x1" checked="checked" class="y1" /> x1</span>
      <span><input type="radio" name="abc" value="x2" class="y2" /> x2</span>
      <span><input type="radio" name="abc" value="x3" class="y3" /> x3</span>
    </div>
    <div class="selectx2">select x2</div>
    <div class="clear"></div>
  </div>
</div>