jQuery:有没有更好的方法来切换两个div? [英] jQuery: Is there a better way to switch two divs?
问题描述
我目前正在使用以下代码块在两个div之间切换.
I'm currently using the following block of code to switch between two divs.
$('.btn-my-projects').click(function(e) {
$('.my-projects').show();
$('.all-projects').hide();
});
$('.btn-all-projects').click(function(e) {
$('.my-projects').hide();
$('.all-projects').show();
});
显然可以,但是我想知道是否有更好的方法可以做到这一点.感觉它可以压缩为一个处理程序,而不是两个.如果我使用委托,则可以使其成为单个处理程序,但是它将变得更长,需要进行条件检查以查看单击了哪个按钮.
Obviously it works but I'm wondering if there's a better way to do this. Feels like it could be compressed down to one handler vs. two. If I use delegation I can make it a single handler but it will become longer, requiring a conditional check to see which button was clicked.
推荐答案
简单:
function toggle(all) {
$('.all-projects').toggle(all);
$('.my-projects').toggle(!all);
}
$('.btn-my-projects').click(function() {
toggle(false);
});
$('.btn-all-projects').click(function() {
toggle(true);
});
如果您想更简洁:
function makeClickHandler(all) {
return function () {
$('.all-projects').toggle(all);
$('.my-projects').toggle(!all);
};
}
$('.btn-my-projects').click(makeClickHandler(false));
$('.btn-all-projects').click(makeClickHandler(true));
或者,您可以采用一种完全不同的方法,并在其中显示&使用HTML5 data-*
属性将哪个div隐藏到标记中.像这样:
Alternately, you could take a completely different approach and put the link between which button shows & hides which div into the markup, using an HTML5 data-*
attribute. Something like this:
<button class="project-control" data-show=".all-projects">
Show all projects
</button>
<button class="project-control" data-show=".my-projects">
Show my projects
</button>
<div class="project all-projects">...</div>
<div class="project my-projects">...</div>
使用这样的JavaScript:
with JavaScript like this:
$('.project-control').on('click', function () {
var showSelector = $(this).data('show');
$('.project').hide();
$(showSelector).show();
});
在实际页面中,您可能希望缓存选定的元素.
N.B. in a real page, you would probably want to cache the selected elements.
这篇关于jQuery:有没有更好的方法来切换两个div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!