我是编程新手,无法弄清楚为什么innerHTML函数不会在屏幕上打印值(我意识到我使用了两个函数,对于这么少量的代码来说似乎是额外的,但这是因为它是为了较大的项目)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="moneyform" name="moneyform">
<fieldset>
<select id="money" name="money" onselect="calculateTotal()">
<option value="loon">1 dollar</option>
<option value="toon">2 dollar</option>
</select>
<br>
<p id="pg"></p>
</fieldset>
</form>
<script type="text/javascript" src="TEST.js"></script>
</body>
</html>
//JAVASCRIPT BELOW
var moneyprice = new Array();
moneyprice["loon"] = 1;
moneyprice["toon"] = 2;
function moneyTotal() {
var mons = 0;
var frm = document.forms["moneyform"];
var selectedMoney = frm.elements["money"];
mons = moneyprice[selectedMoney.value]
return mons;
}
function calculateTotal() {
var total = moneyTotal();
document.getElementById("pg").innerHTML = total;
}
最佳答案
首先,您使用 onselect
事件来启动操作,但是 select
适用于用户选择 text
字段或 textarea
内的文本时。您需要使用 change
事件,该事件在元素值更改时触发。
接下来,您没有正确使用数组,这导致您的结果什么也没有返回。数组具有可存储数据的非负整数索引。它们没有键名来存储数据——对象可以做到这一点。您可以在这里看到,在这些行运行之后,您仍然有一个空数组:
var moneyprice = new Array(); // Ok.
// moneyprice doesn't/can't have a "loon" or a "toon" index
// so neither of these lines accomplish anything
moneyprice["loon"] = 1;
moneyprice["toon"] = 2;
console.log(moneyprice); // Empty array
// ******************************************
// Now, this is how to use an array:
var moneyprice2 = new Array(); // Ok.
// You interact with an Array via its numeric indexes:
moneyprice2[0] = "loon";
moneyprice2[1] = "toon";
console.log(moneyprice2); // Empty array
现在,尚不清楚您试图用该数组做什么,而且似乎您尝试做的事情并没有多大意义 - 您的函数谈论金钱和计算总数,但是您的 select
有字符串值。
最后,您正在使用的代码使用了古老的技术,您确实不应该太习惯使用这些技术。那里有很多糟糕的代码,因此请从信誉良好的来源学习。 The Mozilla Developer Network是一个。
请参阅此缩减后的解决方案,让您了解启动和运行某些内容所需的“移动部件”。请注意所有 JavaScript 是如何与 HTML 分离的。
// Get your element references the proper way.
// No need to get a reference to the form, just to get a reference
// to the select and even if we did want to get a reference
// to the form, we use the modern DOM API to do it (not document[forms]).
let select = document.getElementById("money");
let pg = document.getElementById("pg");
// Set up event handlers in JavaScript, not with HTML attributes
select.addEventListener("change", calculateTotal);
function calculateTotal() {
// .innerHTML should only be used when the string you are dealing with
// contains HTML that needs to be parsed as such. When there isn't any
// HTML, use .textContent
pg.textContent = select.value;
}
<form id="moneyform">
<fieldset>
<select id="money" name="money">
<option value="loon">1 dollar</option>
<option value="toon">2 dollar</option>
</select>
<br>
<p id="pg"></p>
</fieldset>
</form>
关于用于打印 SIMPLE 的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068559/