我在下面有这个简单的jQuery代码,根据2个单选按钮的值显示或隐藏一堆表行。
下面的代码非常适合click事件,但我还想添加在页面加载时有效的代码,在Click事件发生之前它应该根据收音机的值显示或隐藏我的表行按钮。
因此,当页面加载时,如果选择了“是”值的单选按钮,它应该显示表,如果不是,那么它应该隐藏它们。如果没有选择单选按钮,它也应该隐藏它们。
有人可以帮助添加这些添加内容吗?
$('input[type=\"radio\"]').click(function(){
if($(this).attr('value')=='yes'){
$('.showCta').show();
}
if($(this).attr('value')=='no'){
$('.showCta').hide();
}
});
答案 0 :(得分:1)
你可以在下面这样的函数中提取主逻辑,这是因为你不会重复你的代码。
function showTablesByRadio(){
if($(this).attr('value')=='yes'){
$('.showCta').show();
}
if($(this).attr('value')=='no'){
$('.showCta').hide();
}
}
点击收音机&对于负载上的每个无线电。
$('input[type=\"radio\"]').click(showTablesByRadio);
$(document).ready(function(){
$('input[type=\"radio\"]').each(showTablesByRadio);
})
答案 1 :(得分:1)
使用.val()
和change
事件。此外,您不需要转义\"
$('input[type="radio"]').change (function(){
if($(this).val() =='yes'){
$('.showCta').show();
}
if($(this).val() == 'no'){
$('.showCta').hide();
}
}).change(); //Trigger intially
答案 2 :(得分:1)
这应该是一个非常简单的修复,因为您拥有的所有当前代码仍然可以工作。试试这个:
以下内容处理页面就绪:
$(document).ready( function() {
var $x = $('input[type=\"radio\"]');
if($x.attr('value')=='yes'){
$('.showCta').show();
}
if($x.attr('value')=='no'){
$('.showCta').hide();
}
});
并保留事件处理程序:
$('input[type=\"radio\"]').click(function(){
if($(this).attr('value')=='yes'){
$('.showCta').show();
}
if($(this).attr('value')=='no'){
$('.showCta').hide();
}
});
答案 3 :(得分:1)
你可以这样做:
HTML:
<input id='yes' type='radio' name='check' checked>Yes</input>
<input id='no' type='radio' name='check'>No</input>
<button id='button'>Button</button>
JS:
$(document).ready(function() {
if (document.getElementById('yes').checked) {
$('#button').show();
} else {
$('#button').hide();
}
});
答案 4 :(得分:1)
虽然到目前为止发布的答案有效,但我仍然建议进一步修改以稍微压缩你的代码(你使用的是jQuery,其口号是:“少写,多做。”利用它) :
// You don't need to escape the quotes (unless you delimit the string with
// the same quotes you use within your string).
// bind event-handling to the 'change' event:
$('input[type="radio"]').change(function(){
// because this should only execute according the condition of the
// checked 'input' element:
if (this.checked){
// show, or hide, the element(s) according to the assessment evaluating
// to true (show) or false (hide):
$('.showCta').toggle(this.value === 'yes');
}
// trigger the change event, and thus the change-event handling, on page-load:
}).change();
参考文献: