在for循环javascript中生成变量

时间:2015-07-17 14:31:06

标签: javascript arrays for-loop

我有很多像这样的变量

container = document.getElementById('container_dc');
content = document.getElementById('content_dc');
unexpClickthrough = document.getElementById('unexpClickthrough');
expandedBgExit = document.getElementById('expanded_background_exit_dc');
vidContainer = document.getElementById('video_container_dc');
vid = document.getElementById('video_dc');
vidPlayBtn = document.getElementById('video_control_play_dc');
vidPauseBtn = document.getElementById('video_control_pause_dc');
vidStopBtn = document.getElementById('video_control_stop_dc');
vidReplayBtn = document.getElementById('video_control_replay_dc');
vidUnmuteBtn = document.getElementById('video_control_unmute_dc');
vidMuteBtn = document.getElementById('video_control_mute_dc');
close_btn = document.getElementById('close_btn_dc');
expand_content =  document.getElementById('expand_content_dc');
mainImage = document.getElementById('mainImage');
vertBar_1 = document.getElementById('vertBar_1');
vertBar_2 = document.getElementById('vertBar_2');
vertBar_3 = document.getElementById('vertBar_3');
vertBar_4 = document.getElementById('vertBar_4');
vertBar_5 = document.getElementById('vertBar_5');
vertBar_6 = document.getElementById('vertBar_6');
headline = document.getElementById('headline');
darkener = document.getElementById('darkener');
gradBar = document.getElementById('gradBar');
txt_forToday = document.getElementById('txt_forToday');
stat1 = document.getElementById('stat1');
stat2 = document.getElementById('stat2');
stat3 = document.getElementById('stat3');
stat4 = document.getElementById('stat4');
divider1 = document.getElementById('divider1');
divider2 = document.getElementById('divider2');
divider3 = document.getElementById('divider3');
cta = document.getElementById('cta');
downArrow = document.getElementById('downArrow');
vidPanelBg = document.getElementById('vidPanelBg');
vidPanelCopy = document.getElementById('vidPanelCopy');
legalBut = document.getElementById('legalBut');
legalButExp = document.getElementById('legalButExp');
legalsPanel = document.getElementById('legalsPanel');
legalsPanelExp = document.getElementById('legalsPanelExp');

我想通过使用for循环来缩短它。有没有办法在for循环中复制它而不为它们创建站点的对象?问题是我需要这些变量名保持不变。

2 个答案:

答案 0 :(得分:1)

唯一的冗余就是重复调用document.getElementById()。这些元素的ID是信息:你不能废除它们。做这样的事情:

elementIds = ['container_dc', 'content_dc', ...];

for (var i = 0; i < elementIds.length; i++) {
    var id = elementIds[i];
    window[id] = document.findElementById(id); # same as global var
}

console.log(content_dc) // access them like this

另一方面,我觉得奇怪的是你需要从文档中获取这么多元素。这并不常见:也许您应该考虑一个不需要Javascript操作页面的许多元素的设计。

你拿了很多容器,例如,这很少见:通常,这些是用于布局目的,你在CSS中提到它们,但只与脚本中包含动态信息的元素进行交互。

答案 1 :(得分:0)

你可以创建一个变量名数组,然后使用window对象循环它们来构建赋值:

var ary = ['vertBar_1', 'vertBar_2', 'vertBar_3'];
for (var i = 0; i < ary.length; i++) {
    window[ary[i]] = document.getElementById(ary[i]);
}
console.log(vertBar_1, vertBar_2, vertBar_3)