Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过创建错误数组在Javascript中设置style属性_Javascript_Html_Dom_Html5 Video_Undefined - Fatal编程技术网

通过创建错误数组在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;i
video.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]
列表。谢谢,我将开始使用这种编码方式。