gpt4 book ai didi

javascript - 重构简单的 jQuery 切换选择器

转载 作者:行者123 更新时间:2023-11-29 10:49:26 24 4
gpt4 key购买 nike

我正在将我的代码从 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 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 .

关于javascript - 重构简单的 jQuery 切换选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com