JavaScript函数可打印SIMPLE

时间:2018-10-30 16:11:57

标签: javascript html arrays function

我是编程新手,无法弄清楚为什么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;

}

1 个答案:

答案 0 :(得分:2)

首先,您正在使用onselect事件来开始事情,但是select用于用户选择text字段或textarea内的文本。您将要使用change事件,该事件在元素值更改时触发。

接下来,您无法正确使用Array,这将导致结果无结果。数组具有可以存储数据的非负整数索引。他们没有用于存储数据的键名-对象可以做到这一点。您可以在此处看到这些行运行之后,仍然有一个空数组:

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

现在,无论如何,您都不清楚要使用该数组做什么,而且看来您尝试执行的操作并没有多大意义-您的函数谈论的是金钱并计算总额,但是{ {1}}具有字符串值。

最后,您正在使用的代码使用了古老的技术,您确实不应对此感到太自在。那里有很多不良代码,因此请向信誉良好的源学习。 The Mozilla Developer Network是一个。

请参阅此按比例缩小的解决方案,以使您了解“活动部件”以启动并运行某些产品。请注意如何将所有JavaScript与HTML分开。

select
// 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;
}