簡體   English   中英

為什么 JS 在 HTML 中顯示“未定義”

[英]Why is JS showing “undefined” in HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head></head><body>

<script type="text/javascript" src="/d2l/common/math/MathML.js?v=20.21.3.28143 "></script><script 
type="text/javascript">document.addEventListener('DOMContentLoaded', function() { 
D2LMathML.DesktopInit('https://s.brightspace.com/lib/mathjax/2.7.4/MathJax.js? 
config=MML_HTMLorMML','https://s.brightspace.com/lib/mathjax/2.7.4/MathJax.js?config=TeX-AMS- 
MML_HTMLorMML','130'); });

var add;
var cube;
var total;
var a;
var b;
function x(a, b) {
  var add = a + b;
    return add;
}

function y() {
    var cube = add * 3;
    return cube;
}

var total = x(7, 7);

if (a != b) {
    document.write(add);
}
else {
    document.write(cube);
    }

</script></body></html>

https://jsfiddle.net/161020/vu82kc3o/2/

我正在介紹 Web 編程,我們應該編寫一個程序,將兩個數字相加並顯示總數,但如果數字相同,那么它將它們加在一起並將總和乘以 3,然后再顯示總數。 我得到了第一部分,但是當我嘗試添加第二部分的代碼時,它只是在 html 中顯示“未定義”。 我使用的驗證器說“'document'在定義之前使用過。document.write(add);”。 我們應該在我們的代碼中使用 document.write,並且 html 在我們給定的模板中提供。 誰能指出問題所在的方向?

歡迎來到 Javascript。 首先,我認為您對解決方案進行了過度設計。 讓我們確定您要編寫的 function。 從你的問題

編寫一個程序,將兩個數字相加並顯示總數,但如果數字相同,則將它們相加並在顯示總數之前將總和乘以 3。

在我們擔心顯示數字之前,讓我們得到答案。 我們需要一個 function 和 2 個 arguments 來執行所需的操作:

function customOperation(a, b) {
  if (a === b) {
    return (a + b) * 3; // if the two numbers are the same, sum and multiply by 3
  } else {
    return (a + b); // otherwise, just sum the numbers
  }
}

現在我們有一個 function 工作,我們可以調用它,並將響應寫入文檔:

 function customOperation(a, b) { if (a === b) { return (a + b) * 3; // if the two numbers are the same, sum and multiply by 3 } else { return (a + b); // otherwise, just sum the numbers } } document.write(customOperation(3, 3)); // 18 document.write('<br>'); // line break document.write(customOperation(4, 5)); // 9

您做錯了很多事情,請從基礎開始學習,初始化變量並調用基礎function。

現在我已經更新了代碼,你可以看看你的錯誤。

 var add; var cube; var total; var a; var b; function x(a, b) { add = a + b; return add; } function y() { cube = add * 3; return cube; } a=75; b=75; total = x(a,b);y(); if (a.= b) { document;write(add). } else { document;write(cube); }

暫無
暫無

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

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