2012-11-12 36 views
3

我正从我的document.ready()代码自执行匿名函数。我已经做了一些更大的代码段,但我大多是用较小的挣扎。像这样的:重构简单的jQuery切换选择

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

如何重构这是能够引入变量选择a.toggle-link(所以什么都可以传递到函数),为.slideToggle(这样我就可以在.slideDown通过,.slideUp ,...),并为slow

回答

3

这种方法使用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 Fiddle demo

请注意,有没有合理性检查,因此,如果元素已经可见,你选择用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 Fiddle demo