jQuery:有没有更好的方法来切换两个div?

编程入门 行业动态 更新时间:2024-10-25 12:29:04
本文介绍了jQuery:有没有更好的方法来切换两个div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在使用以下代码块在两个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?

本文发布于:2023-10-22 23:09:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法来   两个   jQuery   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!