我怎样才能避免这个错误?它有效,但我总是看到这个错误,这里是代码:
function Separe(price) {
nStr = Number(document.getElementById(price).value) * 100
nStr += '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1' + ' ' + '$2');
}
return nStr + " Centimes"
}
function Forma(price, dest) {
var handler = function(e) {
document.getElementById(dest).innerHTML = Separe(price)
};
document.getElementById(price).onchange = handler; //line 50
document.getElementById(price).onkeyup = handler;
}
和 HTML:
<input id="prix" type="number" name="prix" min="1" step="1">
<script>
Forma("prix", "hhh"); //profil 148
</script>
<h1 id="hhh" > </h1>
我的页面在加载时发出错误:
Uncaught TypeError: Cannot set property 'onchange' of null formatter.js:50
Forma formatter.js:50
(anonymous function) profil:148
我这样做是为了避免放onchange
两次onkeyup
变量尚未生成,这是错误的原因,但我该如何避免呢?我什至尝试添加所有变量并将它们初始化为空值,但仍然出现错误!