2013-10-27 70 views
0
<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> 

這就是我想要做的。 for循環除了第10行外完全按照預期工作。我希望將添加到該innerHTML的每個元素移動到不同的數量。所以heihachi移動了22px,森林法則移動了31px,等等。爲所有其他名稱和值添加。我所放的是我的嘗試(僞代碼),但它不起作用。我怎樣才能做到這一點?如何在JavaScript for循環中爲每個額外的innerHTML元素更改css

回答

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);  
} 

JS Fiddle demo

我想,然而,希望有兩個陣列之間的明確的相關性,在這種情況下(具有namevalue屬性的每個對象)將所述陣列成對象的數組:

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

如果目標是有測量(22px31px每個元素的左邊),那麼你可以改用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

參考文獻:

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); 
} 
相關問題