2013-04-22 48 views
0

我有很多的这些功能在此刻:重构的jQuery/JavaScript代码

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

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

麻烦的是,我对这些功能10,它看起来笨拙。有没有更优雅的方式来做这种事情?

非常感谢。

+1

给该函数一个统一的名称并将该ID作为参数传递? – dbf 2013-04-22 08:41:09

回答

0

您可以用单行代替那些功能,这样:

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

当然,但这并不妨碍需要其中十个。 – 2013-04-22 08:45:25

+0

+1它确实减少了我的代码 – ale 2013-04-22 09:28:08

0

如果所有的功能看起来一样,你可以做这样的事情

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

并称之为如: -

toggleModal('modal', 'foo'); 
2
function hideModalAndShow(id) { 
    $('.modal').hide(); 
    $('#' + id).show(); 
} 
+0

+1也是一种改进 – ale 2013-04-22 09:28:37

0

将选择器作为参数传递给函数。

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(); 
} 

这种方式,您可以在该模式选择,但如果该模式没有参数移交将采取默认的。