我建议如下:
// declare variables in the local scope:
var names=["heihachi", "forest law"],
values=[22, 31],
// get a reference to the element outside of the loop (once, versus multiple times):
test = document.getElementById('test'),
// create an element in which to wrap the text:
span = document.createElement('span'),
// declare a variable which will become a reference to the node on which we're working:
_tmp;
// to move the element/words around we need to have 'position: relative':
span.style.position = 'relative';
// iterate over the names array:
for (var i = 0, len = names.length; i < len; i++)
{
// working on a clone of the 'span':
_tmp = span.cloneNode();
// appending a child textNode to that node:
_tmp.appendChild(document.createTextNode(names[i]));
// setting the left property of the Node's style object:
_tmp.style.left = values[i] + 'px';
// appending the node to the 'test' node:
test.appendChild(_tmp);
}
JS 小提琴演示。
但是,我更愿意在两个数组之间建立明确的关联,在这种情况下,将数组转换为对象数组(每个对象都有一个name
andvalue
属性):
var namesAndPositions = [{
'name' : 'heihachi',
'value' : 22
},{
'name' : 'forest law',
'value' : 31
}],
test = document.getElementById('test'),
span = document.createElement('span'),
_tmp;
span.style.position = 'relative';
for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
_tmp = span.cloneNode();
_tmp.appendChild(document.createTextNode(namesAndPositions[i].name));
_tmp.style.left = namesAndPositions[i].value + 'px';
test.appendChild(_tmp);
}
JS 小提琴演示。
如果目标是进行测量(22px
并且31px
在每个元素的左侧),那么您可以改为使用display: inline-block
并设置marginLeft
HTMLElement-node 的属性:
// everything above this point in the code remains the same
span.style.display = 'inline-block';
for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
_tmp = span.cloneNode();
_tmp.appendChild(document.createTextNode(namesAndPositions[i].name));
_tmp.style.marginLeft = namesAndPositions[i].value + 'px';
test.appendChild(_tmp);
}
JS 小提琴演示。
参考: