下面有一个简单的 jQuery 代码,它根据 2 个单选按钮的值显示或隐藏一堆表行。
下面的代码非常适合单击事件,但我还想添加在加载页面时起作用的代码,在单击事件发生之前,它应该根据单选按钮的值显示或隐藏我的表格行按钮。
因此,当页面加载时,如果选择"is"值的单选按钮,则应显示表格,如果否,则应隐藏它们。如果没有选择单选按钮,它也应该隐藏它们。
有人可以帮忙添加这些内容吗?
$('input[type=\"radio\"]').click(function(){
if($(this).attr('value')=='yes'){
$('.showCta').show();
}
if($(this).attr('value')=='no'){
$('.showCta').hide();
}
});
最佳答案
虽然到目前为止发布的答案有效,但我仍然建议进一步更改以压缩您的代码(您使用的是 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();
引用文献:
关于javascript - 根据单选按钮值显示或隐藏表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314698/