Referanceerror when running script

Asked

Viewed 32 times

1

The Code below changes the innerHTML of a DIV and when I run the function item.Footer(); the javascript console tells me "Referanceerror 'item is not defined?"

 (function() {var item ={
	Name: "site-info"
	Html: "Powered by <a target='_blank' href='https://www.twitter.com/FRNathan13'></a>"
	Footer: function(){
		document.getElementById(item.Name).innerHTML=item.Html;
	}
 }
}
<div id="site-info"><button onclick="item.Footer();">MUDAR DIV!</button></div>

1 answer

5


You are defining that object within a function. This makes the variable/object not accessible in the global scope that HTML runs in. To solve this you can use window.item = {} but in that case loses reason to use (function(){...})();...

jsFIddle: http://jsfiddle.net/v0fc52ms/

The best thing would be to add an event receiver within that function instead of having onclick in HTML. Something like:

(function () {
    var item = {
        Name: "site-info",
        Html: "Powered by <a target='_blank' href='https://www.twitter.com/FRNathan13'></a>",
        Footer: function () {
            this.parentNode.innerHTML = item.Html;
        }
    }
    document.querySelector('#' + item.Name + ' button').addEventListener('click', item.Footer);
})();

jsFiddle: http://jsfiddle.net/v0fc52ms/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.