<div id="test"></div>
<script type="text/javascript">
window.names=["heihachi", "forest law"];
window.values=[22, 31];
len=names.length
for (var i = 0; i < len; i++)
{
document.getElementById('test').innerHTML+= names[i];
//names[i].css=margin-left: values[i]px;//
}
</script>
这就是我想做的。除了第10行之外,for循环完全按预期工作。我希望添加到该innerHTML的每个元素都可以移动不同的数量。所以heihachi移动超过22 px,森林法移动超过31 px等。添加所有其他名称和值。我放在那里的是我的尝试(伪代码),但它不起作用。我怎样才能做到这一点?
答案 0 :(得分:1)
我建议如下:
// 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);
}
但是,我希望在两个数组之间有明确的关联,在这种情况下,将数组转换为一个对象数组(每个对象都有name
和value
属性):< / p>
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);
}
如果目标是在每个元素的左侧进行该度量(22px
和31px
),那么您可以使用display: inline-block
并设置marginLeft
属性HTMLElement节点:
// 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);
}
参考文献:
答案 1 :(得分:0)
这是一个更简单的例子:
window.names=["heihachi", "forest law"];
window.values=[22, 31];
var len=names.length;
var test = document.getElementById('test');
for (var i = 0; i < len; i++)
{
var elm = document.createElement("span")
elm.innerHTML = names[i];
elm.style.marginLeft = values[i] + 'px';
test.appendChild(elm);
}