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

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

如何使用 javascript 對 Select 類中的 2 個變量求和?

如何使用 javascript 對 Select 類中的 2 個變量求和?

收到一只叮咚 2022-05-26 16:32:53
我根本沒有做任何javascript,我試圖從選擇類中總結2個值。我可以將它們都顯示出來,但沒有總結出來。誰能解釋為什么我得到“[object HTMLParagraphElement]”作為答案?謝謝function GetSelectedValue1() {    const f = document.getElementById("value1");    const result = f.options[f.selectedIndex].value;    document.getElementById("result").innerHTML = result;    const e = document.getElementById("value2");    const result2 = e.options[e.selectedIndex].value;    document.getElementById("result2").innerHTML = result2;    const g = +result + result2;    document.getElementById("result3").innerHTML = result3;}HTML(它很笨拙,只是在測試): <div class="container vertical-center d-flex justify-content-center" id="stock-box">            <ul class="list-group">                <li class="list-group-item d-flex justify-content-between align-items-center list-group-item-action">                    <b>Order:</b>                    <div class="btn-group">                        <select class="custom-select" name="stock-box-margin40" id="value1">                            <option selected>Choose Quantity</option>                            <option value="1">1</option>                            <option value="2">2</option>                            <option value="3">3</option>                            <option value="4">4</option>                            <option value="5">5</option>                            <option value="6">6</option>                            <option value="7">7</option>                            <option value="8">8</option>                            <option value="9">9</option>                            <option value="10">10</option>                        </select>                        <p id="result">United State</p>                        <button type="button" onclick="GetSelectedValue1()">Get Selected Value</button>                    </div>                </li>
查看完整描述

1 回答

?
夢里花落0921

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

你得到[object HTMLParagraphElement]是因為你在控制臺記錄 HTML 元素本身,這里是result3. 您實際上應該記錄的是g. 因為那是您存儲字符串添加的地方。


這不過是一個粗心的錯誤。


替換result3為g,


// If you want to perform string addition

const g = result + result2; 


// If you want to perform numerical addition


// Using bitwise or (|) is the fastest way to convert string to number in JS

// You can also save a few bytes in your JavaScript code by using 

// the | (bitwise-or) operator instead of parseInt or 

// uniary opertor (+) as addressed in the comment section

const g = (result | 0) + (result2 | 0);


document.getElementById("result3").innerHTML = g; // not result3


查看完整回答
反對 回復 2022-05-26
  • 1 回答
  • 0 關注
  • 110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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