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

前端 未结 5 1150
忘了有多久
忘了有多久 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:09

    You should modify the function like so, for it to work. If you want to use setAttribute then you will have to wrap it in a function for the onBlur event

     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", function() {
              para.innerHTML = textbox.value;
         });
         document.body.appendChild(textbox);
     }
    

    Or you can checkout the jsfiddle, to see how it works.

    It was recommended to check in a previous answer, if the element is null, but in this case it's not needed as you are creating all the elements in the functions, so all elements will exist.

    Also what do you plan to do with the paragraph element? Maybe wrap the input in the paragraph?

    If you want you can add the paragraph simply by adding

    document.body.appendChild(para);
    

提交回复
热议问题