HTML error cannot set property of null (anonymous function)

廉价感情. 提交于 2021-01-28 11:58:54

问题


I'm trying to store a textbox value to local storage however I'm catching an Uncaught TypeError: Cannot set property 'onclick' of null and not sure exactly why. Everything seems to be referenced correctly. Any insight would be appreciated.

<script type="text/javascript">
var save_button = document.getElementById('Save')
save_button.onclick = saveData;

function saveData()
{
    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.value);
    var storedValue = localStorage.getItem("server");
};
</script>    

<label for="serveri">Server:</label>
<input type='text' name="server" id="saveServer" />
<button onclick="saveData()" type="button" value="Save" id="Save">Save</button>

If the above doesn't show my problem, here is the whole in JSFiddle: http://jsfiddle.net/mGfeu/


回答1:


Write the script after the body. The DOM isn't loaded when your script executes. Hence there is no element with id 'Save'.




回答2:


Your code is run before the DOM is ready (so the .getElementById cannot find your element)

Change your code to

// attach events for all browsers
var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
  document[eventName](prefix + "load", init, false);


function init() {
    var save_button = document.getElementById('Save');
    save_button.onclick = saveData;
}

function saveData() {
    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.value);
    var storedValue = localStorage.getItem("server");
    alert(storedValue);
}



回答3:


You are looking for the element before it is rendered on the page.

Your fiddle is messed up since you included the script block in the HTML markup and in the JavaScript panel. The one in the HTML markup is firing the error since it is not running at onload or document ready.




回答4:


Your fiddle works if you take out the script (you just need to include the html from the body) and put it in the js area only, because that is using an onload script to render:

http://jsfiddle.net/spacebean/mGfeu/1/

It's returning the localStorage element correctly and everything is being set fine.

For your code just make sure to wrap it in an onload event, e.g.:

<script type="text/javascript">
//<![CDATA[
    window.onload=function(){ /* your js here */ }
//]]>



来源:https://stackoverflow.com/questions/19542813/html-error-cannot-set-property-of-null-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!