javascript - 未捕获的引用错误:未在 HTMLSpanElement.onclick 中定义
问题描述
我是 JavaScript 新手。我正在制作一个基于 js 的计算器,每当我单击“计算”按钮时,都会出现两个错误。我尝试在脚本中将“$”更改为“jQuery”,但没有帮助。我尝试更改按钮中的 html,但没有帮助。js脚本已经在其他网站上运行过,所以不是这样。这是我调用它或在我的 html 中引用它的方式。
错误一:
Uncaught ReferenceError: veganCalc is not defined at HTMLSpanElement.onclick
错误2:
Uncaught SyntaxError: Unexpected token '<'
这是我的 JS 代码:
<script>
var formatNumber = function (x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
var kgToLb = function () {
return v * 2.20462;
};
var lbToKg = function () {
return v / 2.20462;
};
var gallonToLitre = function () {
return v * 3.7854;
};
var litreToGallon = function () {
return v / 3.7854;
};
var sqftToSqm = function () {
return v * 0.0929;
};
var sqmToSqft = function () {
return v / 0.0929;
};
function veganCalc () {
var unit;
var totalDays = 0;
var years = $('#years').val();
var month = $('#months').val();
totalDays = (month) ? totalDays + month*30 : totalDays ;
totalDays = (years) ? totalDays + years*365 : totalDays ;
// Variables
var indexes = {
'gallons': {
'ipd': {
'imperial': 1100,
'metric': 4163.9
},
'selector': '.water',
'index': {
'imperial': 'Gallons of water:',
'metric': 'Litres of water:'
}
},
'grains': {
'ipd': {
'imperial': 40,
'metric': 18.1
},
'selector': '.grain',
'index': {
'imperial': 'lbs of Grain:',
'metric': 'kg of Grain:'
}
},
'forest': {
'ipd': {
'imperial': 30,
'metric': 2.8
},
'selector': '.forest',
'index': {
'imperial': 'Sq.ft of Forest:',
'metric': 'Sq.m of Forest:'
}
},
'co2': {
'ipd': {
'imperial': 20,
'metric': 9.1
},
'selector': '.co2',
'index': {
'imperial': 'lbs of Co2:',
'metric': 'kg of Co2:'
}
},
'animals': {
'ipd': {
'imperial': 1,
'metric': 1
},
'selector': '.animals',
'index': {
'imperial': 'Animal Lives:',
'metric': 'Animal Lives:'
}
}
}
// Functions
var years = $('#years').val();
var months = $('#months').val();
var unit = $('#unit').val();
//Prints
$.map(indexes, function (v, i) {
$(v.selector + ".index").html(v.index[unit]);
$(v.selector + ".value").html(formatNumber( Math.round(v.ipd[unit] * totalDays) ) );
});
$('.intro.index').html("You have saved:");
};
按钮 HTML
<a href="#calculator">
<span class="button postfix calculator-btn" onclick="veganCalc()">Calculate</span></a>
解决方案
我没有用 jQuery 替换所有的 $。一旦我这样做了,一切都会奏效。
推荐阅读
- django - TypeError:“用户”对象不可下标
- node.js - 使用正则表达式从带有节点的 csv 文件中删除 \n 和 \r
- python-3.x - 在熊猫中选择最大值特殊条件?
- javascript - 在 Playframework 中使用 jquery添加
- jupyter-notebook - 如何在谷歌 Colab 上关闭和停止 jupyter notebook
- c - 在 C 中使用 rand() 生成大量双精度时发生分段错误
- mysql - 将 .sql 文件导入 mysql
- javascript - 离子地图在我第一次进入页面时加载,但在导航回来后它不加载
- reactjs - 在 getDerivedStateFromProps 方法中访问以前的道具
- bash - 在 Bash 上获取生成数字的 MODE