重构jQuery/JavaScript代码以显示/隐藏大量的模态窗口

Refactoring jQuery/JavaScript code for showing/hiding a large number of modal windows

本文关键字:模态 窗口 隐藏 显示 jQuery JavaScript 代码 重构      更新时间:2023-09-26

我现在有很多这样的函数:

function show_foo() {
   $('.modal').hide(); // hide all modals
   $('#foo').show(); // show the foo modal
}
function show_bar() {
   $('.modal').hide();
   $('#bar').show();
}

问题是我有大约10个这样的函数,它看起来很笨拙。有没有更优雅的方法来做这件事?

许多谢谢。

function hideModalAndShow(id) {
   $('.modal').hide();
   $('#' + id).show();
}

您可以用一行替换这些函数,如下所示:

$('.modal').hide().filter('#bar').show();

如果所有的函数看起来都一样,您可以这样做

function toggleModal(classToHide, idToShow) {
   $('.' + classToHide).hide(); // hide all modals
   $('#' + idToSHow).show(); // show the foo modal
}

并将其命名为:-

toggleModal('modal', 'foo');

将选择器作为函数的参数。

function show(selector) {
   $('.modal').hide();
   $(selector).show();
}
show('#bar');

现在你可以提交一个选择器字符串或一个jquery对象。不建议将#移动到函数中,因为这样会降低可重用性,并且更脆弱,但这取决于您的用例。

show('bar');
$('#' + selector).show();

如果类.modal可能会发生变化,您可能希望进一步修改函数,并将模态的选择器作为第二个(可选的)参数。

function show(selector,modal) {
   $(modal?modal:'.modal').hide();
   $(selector).show();
}

这样,可以为模态提供一个选择器,但如果没有为模态提供参数,它将采用默认值。