jQuery-如何针对我的情况减少重复代码

jQuery-如何针对我的情况减少重复代码,jquery,Jquery,这是我的密码 jQuery(document).ready(function() { if(jQuery('input[name="email_notification"]').is(":checked")) jQuery('#your_email').show(); else jQuery('#your_email').hide(); jQuery('input[name="email_notification"]').click(f

这是我的密码

jQuery(document).ready(function() {

    if(jQuery('input[name="email_notification"]').is(":checked"))
        jQuery('#your_email').show();
    else
        jQuery('#your_email').hide();

    jQuery('input[name="email_notification"]').click(function(){
        if(jQuery(this).is(":checked"))
            jQuery('#your_email').show();
        else
            jQuery('#your_email').hide();
    });
});
我有很多代码来做这个乏味的工作。 加载页面时,检查是否选中某个元素并显示/隐藏另一个元素。 然后,绑定一个click事件以再次执行该操作

有没有办法让我的编码生活更轻松

提前谢谢


英语不好,希望一些编辑能给这个问题一个更清晰的标题。

试试这样:

function handleEmailDisplay($EmailContainer)
{
    if($EmailContainer.is(":checked"))
        jQuery('#your_email').show();
    else
        jQuery('#your_email').hide();
}

jQuery(document).ready(function() {

    handleEmailDisplay($('input[name="email_notification"]'))

    jQuery('input[name="email_notification"]').click(function(){
        handleEmailDisplay($(this))
    });

});

只需绑定处理程序并在DOM就绪时触发事件

$(document).ready(function() {
    $('input[name="email_notification"]').change(function(){
        $('#your_email').toggle(this.checked);
    }).change();
});

你有JSP吗?原因是-如果您正在加载元素,您可以通过scriplet设置checked属性吗?