单击 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/