Error: Uncaught TypeError: Cannot read property 'value' of null

前端 未结 5 1146
忘了有多久
忘了有多久 2021-01-29 15:05

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()
                 


        
5条回答
  •  终归单人心
    2021-01-29 15:19

    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.

    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.

    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);
            }
    

提交回复
热议问题