开发者

How do I reference a global variable from within an inline event handler?

JavaScript:

 lang = {'edit': 'Edit'}; // global variable

HTML:

 <select onchange="alert(lang.edit)"> // alerts undefined 

Whenever the event fires, it alerts "undefined". The lang variable is global开发者_如何学运维, so why can't the inline event handler code reference it?


  1. Make sure that the JavaScript file is explicitly setting a global variable:

    window['lang'] = {'edit': 'Edit'};
    
  2. Make sure your event handler code explicitly refers to the global "lang" variable:

    <select onchange='alert(window.lang.edit)'>
    

The 1st one is probably already OK, but I add that just to make sure. The second thing, well, the interpretation of "onfoo" attribute values is subtle and weird. If there's a "lang" attribute of the <select> DOM element or a "lang" attribute on a <form> tag surrounding the <select>, then a reference to the identifier "lang" in the "onclick" value will pick up that instead of the global "lang" you define in the JavaScript file. Your "onclick" value is turned into a function (in order for it to work as an event handler) by a process that looks more-or-less like this:

var handler = new Function("event", "with (this.form) { with (this) { alert(lang.edit); }}");

It's weird, but that's actually what happens with that sort of event handler code.


Every global object in javascript is a property of the window object. So you should write window.lang = {'edit': 'Edit'};

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜