簡體   English   中英

我需要以表格格式打印數組,並能夠添加帶有值的新行

[英]I need to print array in table format and be able to add new row with value

當我按下ADD按鈕時,我沒有將值= 0推入數組並且不會打印出來的問題,我只是在編碼。

<button id="add">ADD</button>
<p id="demo"></p>

<script>
var fruits, text, fLen, i;
fruits = ["0", "1", "2", "3"];

function myFunction() {
 fruits.push("0");
}

function print() {
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

}

window.onload = print();
document.getElementById("demo").innerHTML = text;
document.getElementById("add").addEventListener("click", myFunction);

</script>

您的代碼是正確的,它將新值推送到數組。 但是,僅在窗口加載時才觸發打印數組值的打印函數。

因此,一旦按下新的值,就應該清除舊的打印件,然后再次打印

  var fruits, text, fLen, i; fruits = ["0", "1", "2", "3"]; function myFunction() { fruits.push("0"); console.log(fruits); print(); } function print() { fLen = fruits.length; text = "<ul id='printed-array'>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>"; //I have put this line within print() function scope, so it gets updated with new text variable value document.getElementById("demo").innerHTML = text; } window.onload = print(); document.getElementById("add").addEventListener("click", myFunction); 
 <button id="add">ADD</button> <p id="demo"></p> 

var fruits, text, fLen, i;
fruits = ["0", "1", "2", "3"];

function myFunction() {
 fruits.push("0");
 document.getElementById("demo").innerHTML = print(); // added this to get new value doing print 
}

function print() {
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
return text; // also added this to get return;
}

window.onload = print();
document.getElementById("demo").innerHTML = text;
document.getElementById("add").addEventListener("click", myFunction);

除了獲得新值外,您的函數還不錯,我添加了print()函數的返回值以獲取新值,然后在您推送新值時調用它

您在推送值,但沒有打印出來。 您需要在推入值並更改innerHTML之后調用print()方法。

你的功能應該是

function myFunction() {
 fruits.push("0");
 print();
 document.getElementById("demo").innerHTML = text;
}

小提琴: https//jsfiddle.net/Lgkzsy41/

var fruits, fLen, i;
fruits = ["0", "1", "2", "3"];

function myFunction() {
 fruits.push("0");
 print();
}

function print() {
   var text='<ul>';
   fLen = fruits.length;            
   for (i = 0; i < fLen; i++) {
     text += "<li>" + fruits[i] + "</li>";
   }   
   text += '</ul>'
   document.getElementById("demo").innerHTML = text;
}

window.onload = print();
document.getElementById("add").addEventListener("click", myFunction);

完整的示例jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM