在功能中对var进行分组 [英] Grouping vars in function

查看:39
本文介绍了在功能中对var进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感觉这是如此明显,当(如果)解决时我会感到as愧-但我只是无法使它起作用.

I have a feeling this is so obvious I'll be ashamed when (if) solved - but I just can't make it work.

我有一个html + javascript页面,其中包含多个项目,所有这些项目都需要通过用户点击来显示或隐藏.所以我有x的div数量:

I have a html+javascript page with multiple items all needing to be shown or hidden via user-clicks. So I have x amount of div's like:

<div id="myDIVA" style="display:none;">blabla 1</div>
<div id="myDIVB" style="display:none;">blabla 2</div>
<div id="myDIVC" style="display:none;">blabla 3</div>

,通过单击div可以隐藏和/或显示它们:

and they are hidden and/or shown by clicking div's:

<div onClick="myClickFunctionA()">Show only ONE</div>
<div onClick="myClickFunctionB()">Show only TWO</div>
<div onClick="myClickFunctionC()">Show only THREE</div>

一个简单的脚本去了:

<script>
    var a = document.getElementById('myDIVA');
    var b = document.getElementById('myDIVB');
    var c = document.getElementById('myDIVC');
function myClickFunctionA() {
        a.style.display = 'block';
        b.style.display = 'none';
        c.style.display = 'none';
}
function myClickFunctionB() {
        a.style.display = 'none';
        b.style.display = 'block';
        c.style.display = 'none';
}
</script>

我想做的是能够对var进行分组,这样我就可以拥有类似的功能:

What I would like to do is be able to group the vars so I could have a function like:

function myClickFunctionA() {
        a.style.display = 'block';
        b + c.style.display = 'none';
}

我有很多div!因此,这似乎很愚蠢,但对我来说,能够将var分组"以便更轻松地进行编辑是很有意义的.

I have a lot of div's! So this may seem silly but it would make much sense to me to be able to "group" vars for easier editing.

所以我希望有人为一个简单的解决方案做好准备:-)谢谢

So I hope someone is up for an easy solution :-) Thanks

推荐答案

可能是一个很好的数组用例:

Probably a good usecase for an array:

var elemsById = ["myDIVA","myDIVB","myDIVC"]
 .map(id=>[id,document.getElementById(id)]);

因此,每当我们要显示这些元素之一时,我们都会遍历所有元素,并根据其ID隐藏/显示它们:

So whenever we want to show one of these elements, we iterate over all of them, and hide/show them, depending on their id:

function showThisAndHideRest(showId){
  elemsById.forEach(function([id,el]){
    el.style.display=id===showId?"block":"none";
  });
}

因此您可以这样做:

showThisAndHideRest("myDIVA");

注意:鞋帮使用了一些很酷的ES6功能,并非所有浏览器都支持.而且实际上不需要将id存储在数组中,因为它已经是el( el.id )的一部分,但是我只想使用一些参数解构...

Note: the upper uses some cool ES6 features, which are not yet supported by all browsers. And theres actually no need to store id in the array, as its already part of el (el.id), but i just wanted to use some parameter destructuring...

运行

这篇关于在功能中对var进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆