我目前有很多这样的功能:
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 hideModalAndShow(id) {
$('.modal').hide();
$('#' + id).show();
}
如果所有功能看起来都一样,你可以做这样的事情
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();
如果类.modal
可能会发生变化,您可能需要进一步修改函数并将模态的选择器作为第二个(可选)参数。
function show(selector,modal) {
$(modal?modal:'.modal').hide();
$(selector).show();
}
这样你可以交出模态的选择器,但如果没有交出模态的参数,它将采用默认值。