开发者

Variable value does not change why?

Here's the code:

var popupFirstName;
PopupFirstNameButton.addEventListener('click', function(){
    popupFirstName = 'SomeValue';开发者_运维百科
});

When I alert(popupFirstName) in some other function it says undefined. How can I get the value?


popupFirstName has a scope local to where it is placed, which we don't know from what you've told us. But I imagine it is in a function, so the scope will be local to that function. The function you've defined inherits access to that variable; this is a convenience feature of the language.

If you'd like to make a single instance of the variable that has global scope, write window.popupFirstName.


In which browser are you testing? Firefox needs a third parameter for addEventListener and IE uses a completely different method (attachEvent).

You can try to assign the function to onclick:

PopupFirstNameButton.onclick = function(){
    popupFirstName = 'SomeValue';
};

If you want to learn more about advanced event handling and its cross browser issues, or about JavaScript and events in general, I suggest to read the good articles on quirksmode.org.

It goes without saying that the button has to be clicked before the variable is set and that the function where you call alert(popupFirstName) has to have access to the variable.


make sure this variable is declared in the same block scope as the function calling it.


You're missing the third argument for the addEventListener function. For Firefox for example, you would need:

PopupFirstNameButton.addEventListener('click', function(){
    popupFirstName = 'SomeValue';
}, false);

https://developer.mozilla.org/en/DOM/element.addEventListener

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜