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

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

JavaScript 函數的返回值

JavaScript 函數的返回值

眼眸繁星 2023-08-18 13:59:44
我對 HTML 和 JavaScript 還很陌生。我有一個表格,我可以在其中單擊復選框。JavaScript 函數正在計算選中框的總和,并在 html 文本字段中給出結果。到目前為止,一切都很好?,F在我想隱藏代碼或不隱藏代碼,無論結果低于2還是更高,但我不知道我可以使用哪個值來檢查(在腳本和html中)。該函數傳遞哪個值?怎么稱呼?如何在不破壞函數的情況下使 sum 成為全局變量?我的代碼:function checkTotal() {  var sum = 0;  document.listForm.total.value = '';  for (i = 0; i < document.listForm.choice.length; i++) {    if (document.listForm.choice[i].checked) {      sum = sum + parseInt(document.listForm.choice[i].value);    }  }  document.listForm.total.value = sum;}//alert ("Summe: " + ???);<table>  <form name="listForm">    <tr>      <td>A</td>      <td>Inhalt 1</td>      <td><input type="checkbox" name="choice" value="1" onchange="checkTotal()" /></td>    </tr>    <tr>      <td>B</td>      <td>Inhalt 2</td>      <td rowspan="2" ;> <input type="checkbox" name="choice" value="1" onchange="checkTotal()" /></td>    </tr>    <tr>      <td>Summe:</td>      <td><input disabled type="text" size="2" name="total" value="0" /></td>    </tr>  </form></table>
查看完整描述

3 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

在您的 javascript 文件中,如果您創建一個名為 called 的變量total并將其放在方法之外,則您可以在每次運行 checkTotal 時更新該值。


所以:


var total;


function checkTotal() {

  var sum = 0;


  for (i = 0; i < document.listForm.choice.length; i++) {

    if (document.listForm.choice[i].checked) {

      sum = sum + parseInt(document.listForm.choice[i].value);

    }

  }


  total = sum;

}


function getTotal() {

  return total;

}

然后在您的 html 中,您可以調用getTotal(),它將返回total設置的任何數字。


查看完整回答
反對 回復 2023-08-18
?
米琪卡哇伊

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

該函數傳遞哪個值?


無,您的函數不會返回任何值,因此不會移交任何內容。但是,如果您想返回任何值,可以通過該return語句來實現。


IE:


function checkTotal() {

  var sum = 0;

  document.listForm.total.value = '';


  for (i = 0; i < document.listForm.choice.length; i++) {

    if (document.listForm.choice[i].checked) {

      sum = sum + parseInt(document.listForm.choice[i].value);

    }

  }

  document.listForm.total.value = sum;

  return sum;

}

所以當你調用該函數時你可以保存它的返回值


喜歡 :


var total = checkTotal();

怎么稱呼?


目前它是使用事件偵聽器屬性來調用的。IE。onChange


就像在 javascript 中這樣做一樣


document.querySelectorAll('input[type="checkbox"]')

    .forEach(function(){

        this.addEventListener("change", checkTotal)

    })

如何在不破壞函數的情況下使 sum 成為全局變量?


您只需var sum = 0;在全局范圍內聲明函數外部,如下所示


var sum = 0; 

function checkTotal() {

  sum = 0;

  document.listForm.total.value = '';


  for (i = 0; i < document.listForm.choice.length; i++) {

    if (document.listForm.choice[i].checked) {

      sum = sum + parseInt(document.listForm.choice[i].value);

    }

  }

  document.listForm.total.value = sum;

}

javascript 中的任何函數也從其父函數繼承作用域,因此在聲明函數之前可用的任何內容也可以在函數內部使用(與 php 不同)。


但需要注意的是:使用letand聲明的變量const是塊作用域的。含義:無法從其直接封閉的外部訪問它們{...}


將所有內容放在一起并糾正一些錯誤


最終代碼如下所示。


超文本標記語言


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

    <form name="list-form">

        <table>

            <tr>

                <td>A</td>

                <td>Inhalt 1</td>

                <td><input type="checkbox" name="Inhalt_1" value="1"></td>

            </tr>

            <tr>

                <td>B</td>

                <td>Inhalt 2</td>

                <td><input type="checkbox" name="Inhalt_2" value="1"></td>

            </tr>

            <tr>

                <td>Total:</td>

                <td colspan="2"><input disabled type="text" id="total" name="total" value="0" /></td>

            </tr>

        </table>

    </form>

    <script src="path/to/your/js/file.js" type="text/javascript"></script>

</body>

</html>

JS


var checkboxes = document.forms[0].querySelectorAll('input[type="checkbox"]'),

    inpTotal = document.getElementById('total'),

    sum = 0;


// first we define the checkTotal

function checkTotal() {

    sum = 0;

    checkboxes.forEach(el => {

        if (el.checked) sum += +el.value;

    });

    inpTotal.value = sum;

    // alert(sum);

}


// then we add the event listeners

checkboxes.forEach(el => el.addEventListener("change", checkTotal));

PS:最好的做法是盡可能將所有 javascript 與 html 放在單獨的文件中。


查看完整回答
反對 回復 2023-08-18
?
阿波羅的戰車

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

嘗試一下這個。


我知道這有點復雜,但這是很好的做法


我修復了您的非法 HTML 并將內聯事件處理程序移至一個 eventListener


我給了表單一個 ID,使用名稱已過時且無用


如果您打算提交表單,則需要重命名其中一個復選框,或者如果您在服務器上使用 PHP,則添加到[]名稱以創建一個數組


在這里,我重命名了它們,并給了它們一個用于選擇器的類


document.getElementById("listForm").addEventListener("input", function() {

  let sum = 0;

  const checked = [...this.querySelectorAll(".choice:checked")].map(inp => +inp.value); // get all values from checked and convert to number

  if (checked.length > 0) sum = checked.reduce((a, b) => a + b); // sum them

  console.log(sum)

  document.getElementById("total").value = sum; // show value

  document.getElementById("showwhen2").classList.toggle("hide", sum < 2); // unhide when >= 2

});

.hide {

  display: none;

}

<form id="listForm">

  <table>

    <tbody>

      <tr id="A" +>

        <td>A</td>

        <td>Inhalt 1</td>

        <td><input type="checkbox" class="choice" name="choiceA" value="1" /></td>

      </tr>

      <tr>

        <td id="B">B</td>

        <td>Inhalt 2</td>

        <td><input type="checkbox" class="choice" name="choiceB" value="1" /></td>

      </tr>

      <tr>

        <td>Summe:</td>

        <td><input disabled type="text" size="2" name="total" id="total" value="0" /></td>

      </tr>

    </tbody>

  </table>

</form>


<div id="showwhen2" class="hide">Equal 2</div>


查看完整回答
反對 回復 2023-08-18
  • 3 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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