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

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

創建 <input> 元素時,添加后的 onchange 不屬于其中

創建 <input> 元素時,添加后的 onchange 不屬于其中

湖上湖 2023-12-14 15:46:19
我在表格中添加了一些元素。有一個函數可以添加(tr 和 td)這些元素。函數內部有一個部分:for(var i = 0; i < 4; i++) {    cell = document.createElement("td");    row.appendChild(cell);    cellData = document.createElement("input");    cellData.type = "number";    cellData.min = "0"    cellData.max = "7";    cellData.value = "0";    cellData.onchange = "calculate()";    cell.appendChild(cellData);}這將放置 4 個帶有輸入字段的單元格。我的問題是,onchange 部分不起作用。我知道你可以直接將 onchange 函數添加到輸入中。但在這種形式下它不起作用。我知道這是因為當我在瀏覽器中檢查它時它跳過了 onchange 部分:<td><input type="number" min="0" max="7"></td>它只添加了這些。而且我也沒有從函數中收到消息:function calculate() {    console.log("something");}有人可以給我解決這個問題嗎?感謝您的時間和答復!
查看完整描述

2 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

更好的


cellData.onchange = calculate;

更好


cellData.addEventListener("change",calculate);

最好的,因為它只有一個事件偵聽器:


document.querySelector("#myTable tbody").addEventListener("input",calculate);

例子


const getNum = str => isNaN(str) || str.trim() === "" ? 0 : +str;


const tbody = document.querySelector("#myTable tbody");

const totalSpan = document.getElementById('total');

const calculate = fld => {

  const total = [...tbody.querySelectorAll("[type=number]")].map(fld => getNum(fld.value)).reduce((a, b) => a + b)

  totalSpan.textContent = total;

};


tbody.addEventListener("input", calculate);



const row = document.createElement("tr")

for (let i = 0; i < 4; i++) {

  cell = document.createElement("td");

  cellData = document.createElement("input");

  cellData.type = "number";

  cellData.min = "0"

  cellData.max = "7";

  cellData.value = "0";

  cell.appendChild(cellData);

  row.appendChild(cell);

}

tbody.appendChild(row);

<table id="myTable">

  <tbody>

  </tbody>

</table>

<span id="total"></span>


查看完整回答
反對 回復 2023-12-14
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

var row = window.document.createElement('tr');

document.getElementById("content").appendChild(row);

for(var i = 0; i < 4; i++) {

    cell = document.createElement("td");

    row.appendChild(cell);

    cellData = document.createElement("input");

    cellData.type = "number";

    cellData.min = "0"

    cellData.max = "7";

    cellData.value = "0";

    cellData.onchange = calculate ;

    cell.appendChild(cellData);

    

}

function calculate() {

    console.log("something");

}

<div id="content"> </div>


查看完整回答
反對 回復 2023-12-14
  • 2 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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