重构jQuery/JavaScript代码以显示/隐藏大量模式窗口
我目前有许多这样的职能:重构jQuery/JavaScript代码以显示/隐藏大量模式窗口,javascript,jquery,Javascript,Jquery,我目前有许多这样的职能: function show_foo() { $('.modal').hide(); // hide all modals $('#foo').show(); // show the foo modal } function show_bar() { $('.modal').hide(); $('#bar').show(); } 问题是我有大约10个这样的函数,它看起来很笨拙。有没有更优雅的方式来做这类事情 非常感谢。如果所有函数看起来都一样,
function show_foo() {
$('.modal').hide(); // hide all modals
$('#foo').show(); // show the foo modal
}
function show_bar() {
$('.modal').hide();
$('#bar').show();
}
问题是我有大约10个这样的函数,它看起来很笨拙。有没有更优雅的方式来做这类事情
非常感谢。如果所有函数看起来都一样,您可以这样做
function toggleModal(classToHide, idToShow) {
$('.' + classToHide).hide(); // hide all modals
$('#' + idToSHow).show(); // show the foo modal
}
把这个叫做:-
toggleModal('modal', 'foo');
您可以用一行替换这些函数,如下所示:
$('.modal').hide().filter('#bar').show();
将选择器作为参数传递给函数
function show(selector) {
$('.modal').hide();
$(selector).show();
}
show('#bar');
现在您可以移交选择器字符串或jquery对象。
不建议将#
移动到函数中,因为这样会减少可重用性和更脆弱性,但这取决于您的用例
show('bar');
$('#' + selector).show();
如果类.model
可能会更改,您可能需要进一步修改该函数,并将model的选择器作为第二个(可选)参数
function show(selector,modal) {
$(modal?modal:'.modal').hide();
$(selector).show();
}
通过这种方式,您可以为模式移交一个选择器,但如果没有为模式移交任何参数,它将采用默认值。为函数指定一个统一的名称,并将ID作为参数传递?当然,但这并不妨碍需要十个选择器。
function show(selector,modal) {
$(modal?modal:'.modal').hide();
$(selector).show();
}