簡體   English   中英

如何將我的 html 按鈕值與我創建的變量鏈接? 現在它說將其記錄為 html object 但不是按其價值

[英]How do I link my html button value with the variables i've created? right now it says logs it as an html object but not by its value

async function run() {
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
var num1 = document.getElementById("1");
var num2 = document.getElementById("2");
var num3 = document.getElementById("3");
var num4 = document.getElementById("4");
var num5 = document.getElementById("5");
var num6 = document.getElementById("6");
var num7 = document.getElementById("7");
var num8 = document.getElementById("8");
var num9 = document.getElementById("9");

function addtest(num1, num2) {
  return num1 + num2;
}

console.log(num1);

await context.sync();
});
}

當我記錄它時,它會返回: HTMLButtonElement {} 我希望它記錄它的值 1。

在此處輸入圖像描述 在此處輸入圖像描述

發生這種情況是因為您只能使用當前的 JavaScript 代碼獲取元素本身。 您應該使用innerHTMLinnerTexttextContent屬性來獲取它所持有的值。 請注意,它們都返回一個字符串,因此您應該在使用它之前解析它們的值

在您的情況下,我相信innerHTML是最適用的。 所以,這就是你應該做的:

var num1 = parseInt(document.getElementById("1").innerHTML);

num1num9重復此代碼,您應該對 go 很好。

innerHTML 屬性

來自 W3Schools 的定義:

innerHTML 屬性設置或返回元素的 HTML 內容(內部 HTML)。

下面的示例可以闡明.innerHTML如何更好地工作:

 // From your example: var num1 = document.getElementById('1').innerHTML; console.log("<button> holds:", num1); // From other use cases let h = document.querySelector('#heading').innerHTML; let p = document.querySelector('#paragraph').innerHTML; console.log('<h1> holds: ', h); console.log('<p> holds: ', p);
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>innerHTML Example</title> </head> <body> <!-- Your example --> <button id="1">1</button> <!-- Other use cases --> <h1 id="heading">This is a heading</h1> <p id="paragraph">This is a paragraph</p> </body> </html>

有關詳細信息,請參閱 W3Schools 上的HTML DOM innerHTML 屬性

嘗試這個

 function addtest(num1, num2) { return parseInt(num1.textContent) + parseInt(num2.textContent); }

暫無
暫無

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

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