如何在表中打印数组的单个元素?

时间:2018-06-13 09:15:19

标签: javascript html html5

number是类型数组,它在调用addNumber函数时存储一些数字,并在另一个表中显示该数组,其中一行的id为"输出"。现在在我的单个td元素表中所有的打印数组的元素,但我需要将单个数组元素打印到单个td元素。 我怎样才能做到这一点?

HTML

   <table>
<tr>
<td id="output"></td> // I want every element of the array to print in single //td element.right now all elements of the array are printing in first td element.
<td></td>
<td></td>
... and do on 
</tr>
    </table>

<table>
  <tr>

    <td onClick="addNumber(1)">1</td>
    <td onClick="addNumber(2)">2</td>
    <td onClick="addNumber(3)">3</td>

  </tr>
  <tr>

    <td>4</td>
    <td>5</td>
    <td>6</td>

  </tr>
</table>

的javascript

let number = [];

function addNumber( num) {      
   number.push(num);
   console.log( number );
   document.getElementById("output").innerHTML = number;
}

3 个答案:

答案 0 :(得分:2)

您需要为tr提供ID,并在每次点击时向其添加td。此外,td的值为num,而不是数组的number

let number = [];

function addNumber(num) {
  number.push(num);
  document.getElementById("output").innerHTML += "<td>" + num + "</td>";
}

function deleteNumber() {
  number.pop();
  var output = document.getElementById('output');
   output.removeChild(output.lastChild);
}
<table>
  <tr id="output"></tr>
</table>
<table>
  <tr>
    <td onClick="addNumber(1)">1</td>
    <td onClick="addNumber(2)">2</td>
    <td onClick="addNumber(3)">3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>
<a onClick="deleteNumber()">Delete</a>

答案 1 :(得分:0)

您需要将每个结果附加到tr; :d

&#13;
&#13;
let number = [];

function addNumber( num) {      
   number.push(num);
   dislpayArray(number)
}

function dislpayArray(number){
    var el= document.getElementById("output");
    var output;
    number.forEach(function (item){
      output = '<td>'+item+'</td>';
   })
   el.innerHTML += output; 
}
&#13;
<table>
  <tr id="output">
    
  </tr>
</table>
<table>
  <tr>
    <td onClick="addNumber(1)">1</td>
    <td onClick="addNumber(2)">2</td>
    <td onClick="addNumber(3)">3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个对大表和动态数据

有帮助

$(document).ready(function(){
let number = [];
	$('#clickble td').on('click',function(){
		var value = $(this).html();
		addNumber(value);
	});
	function addNumber(num) {
  number.push(num);
		$('#output').append("<td>" +num+"</td>");
	}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr id="output"></tr>
</table>
<table>
  <tr id="clickble">
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>