javascript 如何避免 TypeError:无法设置 null 的属性“onchange”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16216214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:45:38  来源:igfitidea点击:

How to avoid TypeError: Cannot set property 'onchange' of null

javascript

提问by Abdelouahab Pp

How can I avoid this error? It works, but I've always seen this error, here is the code:

我怎样才能避免这个错误?它有效,但我总是看到这个错误,这是代码:

function Separe(price) {
    nStr = Number(document.getElementById(price).value) * 100
    nStr += '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
        nStr = nStr.replace(rgx, '' + ' ' + '');
    }
    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;
}

and the HTML:

和 HTML:

<input id="prix" type="number" name="prix" min="1" step="1">
<script>
    Forma("prix", "hhh"); //profil 148
</script>
<h1 id="hhh" >&nbsp;</h1>

My page is issuing an error on load:

我的页面在加载时发出错误:

Uncaught TypeError: Cannot set property 'onchange' of null formatter.js:50
Forma formatter.js:50
(anonymous function) profil:148

I did it to avoid to put twice onchangeand onkeyup

我这样做是为了避免把两次onchangeonkeyup

The variable is not yet made, this is the cause of the error, but how do I avoid it? I tried even to add all variable and initialise them as nulls, but still getting the error!

变量尚未生成,这是导致错误的原因,但我该如何避免呢?我什至尝试添加所有变量并将它们初始化为空值,但仍然收到错误!

回答by Henrik Andersson

The only way you can avoid this error entirely is by having the element you're asking for ready in the DOM when you query for it.

完全避免此错误的唯一方法是在查询时在 DOM 中准备好您要求的元素。

Assume you have this HTML:

假设你有这个 HTML:

<span id="monkey">Hey I'm a monkey</span>
Result for hopeful monkey:<span id="result"></span>
Result for not so hopeful monkey:<span id="noresult"></span>

and this javascript:

和这个javascript:

var hopefulMonkey = document.getElementById("monkey");
document.getElementById("result").innerHTML = hopefulMonkey;

var notSoHopefulMonkey = document.getElementById("noMonkeys");
document.getElementById("noresult").innerHTML = " "+notSoHopefulMonkey;

The output would be:

输出将是:

Hey I'm a monkey 
Result for hopeful monkey:[object HTMLSpanElement] 
Result for not so hopeful monkey: null

You're therefore trying to access an element that obviously doesn't exist yet or at all if you're getting that error.

因此,如果您收到该错误,您将尝试访问一个显然尚不存在或根本不存在的元素。

That said, you have something else that's causing your trouble since the code you've posted works in Chrome. What version are you running?

也就是说,由于您发布的代码在 Chrome 中有效,因此您还有其他问题导致您遇到麻烦。你运行的是什么版本?

I made a fiddle of your problem: http://jsfiddle.net/EqtQz/

我对你的问题做了一个小提琴:http: //jsfiddle.net/EqtQz/

I made a fiddle demonstrating my answer as well: http://jsfiddle.net/vB2Jp/1/(it has monkeys so it's fun too!)

我也做了一个小提琴来展示我的答案:http: //jsfiddle.net/vB2Jp/1/(它有猴子,所以也很有趣!)

回答by Abdelouahab Pp

it seems that i was a duplicate function in the code! the page uses accordion effect, and the function is called twice (buy area, and sell area), and it was bizarre that even the idwere different, the code alerts errors; but ONLY THE FIRST CALL WORK, NOT THE SECOND.

看来我是代码中的重复函数!页面使用了手风琴效果,函数被调用了两次(买入区和卖出区),奇怪的是,即使id是不同的,代码也提示错误;但只有第一个调用有效,而不是第二个。

in the second it was an id different:

第二个是不同的id:

<script>
Forma("hh", "max");
</script>

....

....

<script>
Forma("h", "min");
</script>

what i did, is to change to second to

我所做的是更改为第二个

<input .... onkeyup="document.getElementById('h').innerHTML = Separe('min')"  onchange="document.getElementById('h').innerHTML = Separe('min')"/>

and it worked! now Chrome dont alert me even that the first section (buy) will call the function as in my question!

它奏效了!现在 Chrome 甚至不提醒我第一部分(购买)将调用我的问题中的函数!