错误:未捕获的TypeError:无法读取null的属性"value"

Ana*_*S S -3 html javascript

我想知道为什么会出现这个错误"未捕获的TypeError:无法读取null的属性'值'以及我哪里出错了?

 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);
        }
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

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

无论如何,这样做毫无意义,因为你已经有了直接引用新创建元素的变量.编辑哦等等,我看到你正在尝试做什么.

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

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);
        }
Run Code Online (Sandbox Code Playgroud)