在多个元素上使用自定义jQuery函数

时间:2013-12-09 06:12:55

标签: jquery function dry

因此,我尝试使用以下脚本遵循DRY规则。基本上我想要一个简单的方法来在多个元素上使用函数。目前,以下内容仅适用于指定的最后一个,而不是全部三个。我试着将它放入一个没有运气的插件中。 jQuery仍然有点新鲜,非常感谢任何帮助。

以下是正在发生的事情的基本工作:http://jsfiddle.net/947E5/

jQuery(function($) {

    hideShowMetaBoxes = function( page ){

        var tempID = '#page_template'
            template = 'templates/' + page + '.php',
            metabox = '#' + page + '_options';

        if ($(tempID).val() == template) {
            $(metabox).show();
            $(metabox+'-hide').prop('checked', true);
        } else {
            $(metabox).hide();
            $(metabox+'-hide').prop('checked', false);
        }

        $(tempID).change(function() {
            if ($(this).val() == template) {
                $(metabox).show();
                $(metabox+'-hide').prop('checked', true);
            } else {
                $(metabox).hide();
                $(metabox+'-hide').prop('checked', false);
            }
        });

    };

    // Contact Options
    hideShowMetaBoxes('contact');

    // Meet Us Options
    hideShowMetaBoxes('meet_us');

    // Services Options
    hideShowMetaBoxes('services');

});

1 个答案:

答案 0 :(得分:1)

我修改了一些dom(即将类添加到你正在显示的div中)。 这是脚本:

jQuery(function($) {

hideShowMetaBoxes = function( page ){
    $('.templateoption').hide();//added for hidingd all template option divs

    var tempID = '#page_template'
        template = 'templates/' + page + '.php',
        metabox = '#' + page + '_options';

    if ($(tempID).val() == template) {
        $(metabox).show();
        $(metabox+'-hide').prop('checked', true);
    } else {
        $(metabox).hide();
        $(metabox+'-hide').prop('checked', false);
    }
     };
});
$('#page_template').change(function(){
 hideShowMetaBoxes($("#page_template option:selected").text().toLowerCase().replace(/ /g,"_"));
});

<强> Working Demo

相关问题