簡體   English   中英

重構簡單的 jQuery 切換選擇器

[英]Refactor simple jQuery toggle selector

我正在將我的代碼從 document.ready() 移動到自執行匿名函數。 我已經完成了一些較大的代碼片段,但我主要是在處理較小的代碼片段。 像這個:

/**
Advanced properties toggle
**/
$('a.toggle-link').click(function (e) {
    $(this).next().slideToggle('slow');
    e.preventDefault();
});

我如何重構它以便能夠為選擇器a.toggle-link引入變量(因此任何東西都可以傳遞到函數中),對於.slideToggle (所以我可以傳入.slideDown.slideUp 、... ) 和slow

這種方法使用 jQuery,但我大部分時間都堅持使用原生 DOM 方法:

function actOnElem(el, method, duration) {
    // if no passed 'el' or 'method' return
    if (!el || !method) {
        return false;
    }
    else {
        // if 'el' is an element-node, use 'el' else assume it's an id
        el = el.nodeType == 1 ? el : document.getElementById(el);
        // duration is used if passed, otherwise 'slow' is used as the default
        duration = duration || 'slow';
        // create a jQuery object from 'el',
        // call the method, if it exists,
        // and use the 'duration'
        $(el)[method](duration);
    }
}

actOnElem(document.getElementById('two'), 'slideDown', 1000);

JS小提琴演示

請注意,沒有健全性檢查,因此如果元素已經可見並且您使用slideDown調用該函數,則不會發生任何事情。 雖然我認為這可以回答您的問題,但我完全不確定您為什么要采用這種方法,而不是直接調用 jQuery 方法。

稍微修改的函數以允許(非常簡單的)故障報告:

function actOnElem(el, method, duration, debug) {
    if (!el || !method) {
        return false;
    }
    else {
        el = el.nodeType == 1 ? el : document.getElementById(el);
        duration = duration || 'slow';
        if ($(el)[method]) {
            $(el)[method](duration);
        }
        else if (debug) {
            console.log('Did you make a typo? There seems to be no "' + method + '" method.');
        }
    }
}

actOnElem(document.getElementById('two'), 'slidedown', 1000, true);
//                                              ^
//                                              +--- typo, should be 'slideDown'

JS小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM