通过创建错误数组在Javascript中设置style属性
获取以下代码中的错误:通过创建错误数组在Javascript中设置style属性,javascript,html,dom,html5-video,undefined,Javascript,Html,Dom,Html5 Video,Undefined,获取以下代码中的错误: var attribute=["position","top","bottom","left","right","zIndex"], prop=["fixed","0","0","0","0","-2"]; for(var i=0;i<attribute.length;i++) video.style.attribute[i]=prop[i]; var属性=[“位置”、“顶部”、“底部”、“左侧”、
var attribute=["position","top","bottom","left","right","zIndex"],
prop=["fixed","0","0","0","0","-2"];
for(var i=0;i<attribute.length;i++)
video.style.attribute[i]=prop[i];
var属性=[“位置”、“顶部”、“底部”、“左侧”、“右侧”、“zIndex”],
道具=[“固定”、“0”、“0”、“0”、“0”、“2”];
for(var i=0;ivideo.style.attribute
尝试读取一个名为attribute
的属性,该属性不存在,因此attribute[0]
抛出观察到的错误
要设置video.style.position=“fixed”
您需要在循环中使用[]
符号:
video.style[attribute[i]] = prop[i];
i、 e.video.style[“position”]=“fixed”
这是一种组织属性和属性的糟糕方法,实际上是一种一般关系:
var attribute=["position","top","bottom","left","right","zIndex"],
prop=["fixed","0","0","0","0","-2"];
维护和扩展非常困难。您应该将键和值关联起来:
var data = {
"position" : "fixed"
,"top" : "0"
,"bottom" : "0"
,"left" : "0"
,"right" : "0"
,"zIndex" : "-2"
}
然后,您应该能够使用1行代码设置属性:
for(key in data) video.style[key] = data[key];
完整示例:
var data = {
"position" : "fixed"
,"top" : "0"
,"bottom" : "0"
,"left" : "0"
,"right" : "0"
,"zIndex" : "-2"
}
for(key in data) video.style[key] = data[key];
你能告诉我更多关于[]符号的信息吗?请看-这是一种在属性名位于变量中时访问对象属性的方法,例如属性[i]
列表。谢谢,我将开始使用这种编码方式。