错误:未被捕获的TypeError:无法读取null的属性“值" [英] Error: Uncaught TypeError: Cannot read property 'value' of null

查看:78
本文介绍了错误:未被捕获的TypeError:无法读取null的属性“值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么会发生此错误未捕获的TypeError:无法读取null的属性'value'"而我要去哪里错了?

i want to know why this error is occuring "Uncaught TypeError: Cannot read property 'value' of null" and where i am going wrong?

 function create()
        {
            var  textbox=document.createElement("input");
            var para=document.createElement("p");
            para.setAttribute("id","p");
            textbox.type='text';
            textbox.value='asdf';
            textbox.setAttribute("id","textbox");
                           textbox.setAttribute("onblur",document.getElementById('p').innerHTML=document.getElementById('textbox').value);
            document.body.appendChild(textbox);
        }

推荐答案

在将元素添加到DOM之前,无法使用 .getElementById()进行搜索.该调用返回 null ,这就是错误告诉您的内容.

Before you've added an element to the DOM, you can't search for it with .getElementById(). That call returns null, and that's what the error is telling you.

无论如何都没有意义,因为您已经有了直接引用您新创建的元素的变量. edit 哦,等等,我明白了您要做什么.

It's pointless to do that anyway, since you've already got variables that refer directly to your newly-created elements. edit oh wait, I see what you're trying to do.

首先,没有理由在此处使用 .setAttribute().只需直接在创建的DOM节点上设置属性即可.您必须将"onblur"属性设置为一个函数:

First, there's no reason to use .setAttribute() here. Just set properties directly on the DOM nodes you've created. You have to set the "onblur" property to a function:

function create() {
            var  textbox=document.createElement("input");
            var para=document.createElement("p");
            para.id = "p";
            textbox.type='text';
            textbox.value='asdf';
            textbox.id = "textbox";
            textbox.onblur = function() {
              para.innerHTML = textbox.value;
            };
            document.body.appendChild(textbox);
            document.body.appendChild(para);
        }

这篇关于错误:未被捕获的TypeError:无法读取null的属性“值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆