Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.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
使用for-in循环在javascript中应用样式_Javascript_For In Loop - Fatal编程技术网

使用for-in循环在javascript中应用样式

使用for-in循环在javascript中应用样式,javascript,for-in-loop,Javascript,For In Loop,因此,我有一个对象,其中充满了描述元素预期样式的键值对,我正试图通过如下方式在对象中循环,将该样式应用于元素: element = document.createElement('div'); style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'} for (x in style){ element.style.x = style[x]; } 但这种元素

因此,我有一个对象,其中充满了描述元素预期样式的键值对,我正试图通过如下方式在对象中循环,将该样式应用于元素:

element = document.createElement('div');   
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
    element.style.x = style[x];
}

但这种元素仍然没有一种风格。这看起来很简单,我无法找出可能出了什么问题,所以我认为我遗漏了一些非常明显的东西。感谢您提供的任何帮助。

您正在为每次迭代设置属性
x
。相反,使用
x
的值,如下所示:

element.style[x] = style[x];

您正在每次迭代中设置属性
x
。相反,使用
x
的值,如下所示:

element.style[x] = style[x];
更改为:

element = document.createElement('div');   
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
    element.style[x] = style[x];
}
更改为:

element = document.createElement('div');   
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
    element.style[x] = style[x];
}