亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我正在使用 for 循環從表單輸入打印輸出,但輸入表單不斷添加自身

我正在使用 for 循環從表單輸入打印輸出,但輸入表單不斷添加自身

呼啦一陣風 2021-09-30 10:26:46
所以我得到了一個關于表單中孩子數量的輸入。如果有 2 個孩子,那么在我單擊按鈕后應該彈出兩個表單,如果是 4 然后是 4。但是我的 for 循環不起作用,由于某種原因,表單的值不斷增加,無論我單擊多少次按鈕,它會無限地繼續添加,當它應該在超過限制時停止。function numbchild() {  z = document.form2;  ax = z.no_child.value;  var i;  for (i = 0; i < parseInt(ax); i++) {    console.log(ax);    document.getElementById('xx').insertAdjacentHTML(      "afterbegin",      "Enter student 's name:   <input type='text ' name='s_name'><br />"    );  }}<form name="form2">  how many children?: <input type="text" name="no_child" size="20" required><br />  <input type="button" name="test" onclick="numbchild()">  <p id="xx"></p></form>
查看完整描述

1 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

如果您的意思是第二次(第三次、第四次)使用按鈕會添加輸入而不是調整那里的總數,那么您的代碼中沒有任何內容試圖避免這種情況。您正在添加輸入的數量。


您可以找出有多少并對此進行調整,請參閱評論:


function numbchild() {

  var z = document.form2;               // *** Added `var`

  var ax = parseInt(z.no_child.value);  // *** Added `var`, parse it just once here

  // *** Get the parent element

  var parent = document.getElementById('xx');

  // *** Get its existing inputs

  var inputs = parent.querySelectorAll("div.input");

  if (inputs.length < ax) {

    // Need to add some

    ax -= inputs.length; // Allow for the ones we already have

    var i;

    for (i = 0; i < ax; i++) { // *** Don't parse it here

      // *** Note wrapping the inputs in divs so

      // its' easy to remove them (and that gives

      // us the line break as well)

      parent.insertAdjacentHTML(

        "beforeend", // *** Add them at the end, not the beginning

        "<div class=input>Enter student 's name:   <input type='text ' name='s_name'></div>"

      );

    }

  } else if (inputs.length > ax) {

    // Need to remove some

    ax = inputs.length - ax;

    while (ax--) {

      parent.removeChild(inputs[inputs.length-1]);

    }

  }

}

<form name="form2">

  how many children?: <input type="text" name="no_child" size="20" required><br />

  <input type="button" name="test" onclick="numbchild()">

  <p id="xx"></p>

</form>


查看完整回答
反對 回復 2021-09-30
  • 1 回答
  • 0 關注
  • 227 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號