[英]Refactoring jQuery/JavaScript code for showing/hiding a large number of modal windows
I have many of these functions at the moment: 我现在有很多这样的功能:
function show_foo() {
$('.modal').hide(); // hide all modals
$('#foo').show(); // show the foo modal
}
function show_bar() {
$('.modal').hide();
$('#bar').show();
}
The trouble is that I have about 10 of these functions and it looks clumsy. 问题是我有大约10个这样的功能,它看起来很笨拙。 Is there some more elegant way to do this sort of thing?
有没有更优雅的方式来做这种事情?
Many thanks. 非常感谢。
function hideModalAndShow(id) {
$('.modal').hide();
$('#' + id).show();
}
If all the functions look like same, you can do something like this 如果所有函数看起来都一样,你可以这样做
function toggleModal(classToHide, idToShow) {
$('.' + classToHide).hide(); // hide all modals
$('#' + idToSHow).show(); // show the foo modal
}
And call this like:- 并称之为: -
toggleModal('modal', 'foo');
您可以用一行替换这些函数,如下所示:
$('.modal').hide().filter('#bar').show();
Hand the selector as an argument to the function. 将选择器作为函数的参数。
function show(selector) {
$('.modal').hide();
$(selector).show();
}
show('#bar');
Now you can hand over a selector string or a jquery object. 现在,您可以移交选择器字符串或jquery对象。 Moving the
#
into the function is not recommended because that would be less reusable and more fragile, but that depends on your usecase. 建议不要将
#
移到函数中,因为它可以重用性更低,更脆弱,但这取决于你的用例。
show('bar');
$('#' + selector).show();
If the class .modal
is subject to change, you may want to modify the function even further and hand the selector for the modal as a second (optional) parameter. 如果类
.modal
可能会发生变化,您可能希望进一步修改该函数,并将模态的选择器作为第二个(可选)参数。
function show(selector,modal) {
$(modal?modal:'.modal').hide();
$(selector).show();
}
This way you can hand over a selector for the modal, but it will take the default if no parameter for the modal is handed over. 这样您就可以移交模态的选择器,但是如果模态的参数没有被移交,它将采用默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.