javascript - 单击时更改 radio 输入值(实际上将其更改回来)

标签 javascript jquery html

单击 selectx2 div 更改 radio 输入选择:

                <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>

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

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

我哪里出错了?

最佳答案

当您使用 .children() 时它找到元素的直接子元素,并且 y2 不是 inputoptions 的直接子元素。

您可以使用.find()

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

使用

    $(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>

关于javascript - 单击时更改 radio 输入值(实际上将其更改回来),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28164953/

相关文章:

javascript - Jquery 不关注 disqus div

jquery - 如何在 jQuery Datatables 中启用特定列的排序而不是禁用特定列

html - 我添加了一个 CSS 动画,但它不起作用,但一切看起来都很好

html - 当有覆盖层时,点击会穿过元素 - 它是如何工作的?

javascript - Grunt 文件对象格式 : All regular files files immediately under top level directory

javascript - 具有相对目标的动态文件映射

php - 为创建的每个 url 打开一个新窗口

html - 在 iOS 11 上使用自定义字体从 HTML 生成 PDF

javascript - 如何记录 Vue 的计算属性或方法?

javascript - 使用 jquery 更改文本,无法正确转换