Javascript 复制字符串的简写方法
我在一个函数中有这段代码,并且想缩短它 - 它将相同的样式应用于数组中的每个项目。
document.getElementById(divsArray[0]).style.visibility = 'hidden';
document.getElementById(divsArray[1]).style.visibility = 'hidden';
document.getElementById(divsArray[2]).style.visibility = 'hidden';
document.getElementById(divsArray[3]).style.visibility = 'hidden';
迄今为止没有答案有效(因为我循环通过代码??)
通过仅将先前显示的幻灯片可见性设置为隐藏来解决它
x = i;
i = i+1;
document.getElementById(divsArray[x]).style.visibility = 'hidden';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用循环怎么样:
How about using a loop:
只是为了提供一些不同的东西,一个 jQuery 解决方案:
编辑:看起来您可能必须首先收集 DOM 引用。 (divsArray 实际上只是一个 div 名称数组,而不是 div 本身?)
Just to provide something different, a jQuery solution:
Edit: It looks like you might have to collect your DOM references first. (divsArray is really just an array of div names, and not the divs themselves?)
在我看来,可能会有更多的 div...我可以建议对 Darin 的代码进行这样的更改:
It sounds to me that there might be more divs... Might I suggest this change to Darin's code:
以下是它在 Prototype 和 Mootools:
And here's how it works in both Prototype and Mootools:
您可以将以下函数放在 divsArray 的相同/后代范围中。
然后你可以做
或者
它看起来毫无意义,但如果你有更多这样的数组,你可能想像这样修改你的函数:
并循环遍历任何数组,如下所示:
不,没有宏,也没有模板。
You can put the following function in the same/descendant scope of divsArray.
Then you can do either
or
It looks pointless, but if you have more arrays like that, you may want to modify your function like this:
and loop through any array like this:
And no, there are no macros nor are there templates.
只要我们都在努力,我就会采取最直接的方法 :D
并且违背常理:
as long as we're all piling on, i'll take the most direct approach :D
and just to go against the grain:
我无法“抗拒”这个挑战。我想说你将它们添加到同一个类中并执行类似的操作(原型示例):
I couldn't "resist" to the challenge. I would say you add them the same class and do something like (Prototype example):
我们可以使用 id 的数组="nofollow noreferrer">
Array.prototype.forEach()
和 ES6 的 箭头函数:We can iterate over array containing
id
s usingArray.prototype.forEach()
and ES6's Arrow Functions: