我正在将我的代码从 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);
请注意,没有完整性检查,因此如果元素已经可见并且您使用 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'
关于javascript - 重构简单的 jQuery 切换选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346031/