【问题标题】:Show and Hide hidden <div> when radio input is checked检查无线电输入时显示和隐藏隐藏的 <div>
【发布时间】:2014-01-08 18:41:01
【问题描述】:
我只想多次使用此功能,而不必复制脚本,或者如果我需要再次使用它,我会自己添加新的选择器。如果你不明白我想说什么,这是我的fiddle。
$('.show-and-hide-content').click(function () {
// Hide all
$('.show-and-hide-true').hide('slideToggle');
// Show checked
if ($('#select-no').prop('checked')) {
$('.show-and-hide-true').show('slideToggle');
}
});
【问题讨论】:
标签:
jquery
radio-button
show-hide
【解决方案1】:
您对不同的操作使用相同的类和 id。看看这个修改后的fiddle
$('.show-and-hide-content').click(function () {
// Hide all
$('.show-and-hide-true').hide('slideToggle');
// Show checked
if ($('#select-no').prop('checked')) {
$('.show-and-hide-true').show('slideToggle');
}
});
$('.show-and-hide-content2').click(function () {
// Hide all
$('.show-and-hide-false').hide('slideToggle');
// Show checked
if ($('#select-yes2').prop('checked')) {
$('.show-and-hide-false').show('slideToggle');
}
});
【解决方案2】:
Working jsFiddle Demo
HTML
<div class="show-and-hide-content">
<input type="radio" data-type="true" />Yes
<input type="radio" data-type="false" />No
<div class="content content-false">You select NO</div>
<div class="content content-true">You select YES</div>
</div>
<div class="show-and-hide-content">
<input type="radio" data-type="true" />Yes
<input type="radio" data-type="false" />No
<div class="content content-false">You select NO</div>
<div class="content content-true">You select YES</div>
</div>
<!-- other duplicates - same markup -->
CSS
.show-and-hide-content .content { display: none; }
.show-and-hide-content .content-false { color: red; }
.show-and-hide-content .content-true { color: green; }
jQuery
>
$(function () {
$('.show-and-hide-content').each(function (i) {
var $row = $(this);
var $radios = $row.find('input');
$radios.attr('name', 'group-' + i);
$radios.on('change', function () {
var type = $(this).attr('data-type');
$row
.find('.content').hide()
.filter('.content-' + type)
.show();
});
});
});
【解决方案3】:
您的意思是这样,当检查值为“是”时,您想显示绿色文本。并在选中“NO”值时显示红色文本?
您也可以仅使用此脚本使用“.show-and-hide-content”的多个 div。
演示http://jsfiddle.net/yeyene/wfA6m/7/
然后,将无线电的 id 更改为类并使用此脚本。
JQUERY
$('.show-and-hide-content').click(function () {
if ($('input.select-no:checked').prop('checked')) {
$(this).find('div.show-and-hide-false').show('slideToggle');
$(this).find('div.show-and-hide-true').hide('slideToggle');
}
else{
$(this).find('div.show-and-hide-true').show('slideToggle');
$(this).find('div.show-and-hide-false').hide('slideToggle');
}
});