我建議如下:
// 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 Fiddle demo。
我想,然而,希望有兩個陣列之間的明確的相關性,在這種情況下(具有name
和value
屬性的每個對象)將所述陣列成對象的數組:
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 Fiddle demo 。
如果目標是有測量(22px
和31px
每個元素的左邊),那麼你可以改用display: inline-block
並設置HTML元素節點的marginLeft
屬性:
// 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 Fiddle demo。
參考文獻: