简体   繁体   English

如何使用对象显示文本内容

[英]How to display.textcontent with objects

How do I iterate through an object that will be displayed on the webpage by using display.textContent. 如何使用display.textContent遍历将在网页上显示的对象。

Given that 鉴于

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.

I want to be able to display 1, but then after a button is clicked, it will than display 2, 3, etc.. How could I do that? 我希望能够显示1,但是单击一个按钮之后,它将显示2、3等。我该怎么做?

You don't store previous value of div.textContent , so you see only last iteration result. 您不存储div.textContent先前值,因此仅看到最后的迭代结果。 Try this 尝试这个

   var list = {x:1, y:2, z:3};
   div.textContent = "";
   for (var property in list){
       div.textContent = div.textContent + " " + (list[property]);
   } 

You could try something like this: 您可以尝试这样的事情:

  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> 

How to display 1,2,3 every time a button is clicked? 每次单击按钮时如何显示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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM