javascript - 根据单选按钮值显示或隐藏表格行

标签 javascript jquery

下面有一个简单的 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();

JS Fiddle demo .

引用文献:

关于javascript - 根据单选按钮值显示或隐藏表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314698/

相关文章:

jquery - 您是否需要将 jQuery.when 与单个延迟对象一起使用?

jquery - 如何 iframe 。内容窗口。文档 。 execCommand 工作?

javascript - "The requested resource does not support http method ' POST' - 405 响应

javascript - window 未定义 angular 通用第三库

javascript - 谨防javascript的痛点要当心

jquery - 分别为每个元素运行函数?

javascript - 添加超时功能以通过 cookie 显示模态

javascript - 使用 Jquery 设置时,占位符在 IE 11 中不起作用

javascript - 如何在同一页面上并排运行 2 个单独的 PaperJS Canvas 项目?

javascript - 当存在 constructor() 时调用异步函数