javascript 未捕获的类型错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5964164/
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-25 18:58:02  来源:igfitidea点击:

Uncaught TypeError

javascriptjqueryhtmlbrowser

提问by Daniel Afonso

Can anyone explain what is theses errors?

谁能解释一下这些错误是什么?

Uncaught TypeError: Cannot set property 'innerHTML' of null

Uncaught TypeError: Cannot read property 'style' of null

Uncaught SyntaxError: Unexpected token ILLEGAL

Uncaught TypeError: Object # has no method 'dispatchEvent'

未捕获的类型错误:无法设置 null 的属性“innerHTML”

未捕获的类型错误:无法读取 null 的属性“样式”

未捕获的语法错误:意外的令牌非法

未捕获的类型错误:对象 # 没有方法“dispatchEvent”

This is my test Website

这是我的测试网站

回答by Paolo Stefan

At some point in the page you have:

在页面中的某个点,您有:

function display_price(price, oid)
{
    ...

    element = document.getElementById(oid);
    if (valor != 'NaN' && valor != null && valor != '')
    {
       element.innerHTML = valor + money_simbol;

The last line is causing the error because elementis null. You should add a condition to the if(): that is, change this line:

最后一行导致错误,因为它element为空。您应该在 if(): 中添加一个条件:即更改此行:

if (valor != 'NaN' && valor != null && valor != '')

to this:

对此:

if (element && valor != 'NaN' && valor != null && valor != '')

In other words, it's a good practice to alwayscheck the return value of a function beforeaccessing its properties.

换句话说,访问其属性之前始终检查函数的返回值是一种很好的做法。

回答by Shadow Wizard is Ear For You

You call the function display_pricepassing it ID of spanthat does not yet exist.

你调用函数display_price传递它的 IDspan还不存在。

Change this line: (appears twice in your code)

更改此行:(在您的代码中出现两次)

display_price('510', 'products_price_id');

To this instead:

改为:

window.onload = function() {
   display_price('510', 'products_price_id');
};

This will wait until the page loads before trying to find the element, thus solve your errors.

这将等到页面加载后再尝试查找元素,从而解决您的错误。