[英]How to display.textcontent with objects
如何使用display.textContent遍歷將在網頁上顯示的對象。
鑒於
var list = {x:1, y:2, z:3};
for (var property in list){
div.textContent = (list[property])
}
//Displays 3.
//Div is referring to my HTML page.
我希望能夠顯示1,但是單擊一個按鈕之后,它將顯示2、3等。我該怎么做?
您不存儲div.textContent
先前值,因此僅看到最后的迭代結果。 嘗試這個
var list = {x:1, y:2, z:3};
div.textContent = "";
for (var property in list){
div.textContent = div.textContent + " " + (list[property]);
}
您可以嘗試這樣的事情:
var list = {x:1, y:2, z:3}, index = 1, // Store the current iteration keys = Object.keys(list); // Grab all the keys for the object var button = document.querySelector("button"), div = document.querySelector("div"); // Bind your click handler button.addEventListener("click", function() { // Might want to do something after '3' if(index >= keys.length) return; // Otherwise set the content from the key at 'index' and increment // the index for the next click div.textContent = list[keys[index++]]; });
<div>1</div> <button>Next</button>
每次單擊按鈕時如何顯示
1,2,3
?
function displayResult(){ var list = {x:1, y:2, z:3}; var div = document.querySelector("#myDiv"); //getting my div element var text = new Array(); for (var property in list){ text.push(list[property]) //adding values in text array } div.textContent = text.join(",") //array concatenation }
<div id="myDiv"></div> <button onclick="displayResult()">Display</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.