Calling this in a Javascript function called by innerHTML
I'm creating a Windows 7 gadget and allowing a user to log-in through the gadget. The gadget will be logging into any valid (as defined by the application domain) address the user provides. Now here I am running into a problem. I do something like this:
function Object(address){
this.address = address
....
this.loginBox = gDocument.createElement("loginBox");
this.loginBox.innerHTML = "<FORM name = 'myForm' action='' method='GET'><input type='text' name='usernameBox' id = 'usernameBox' VALUE=''><input type='password' id = 'passwordBox'><button type = 'button' value = 'Ok' id = 'loginButton' onclick='login()'></FORM>";
(Note: If anyone could format the above code that would be nice but it's not necessary to know exactly what's going on just to know the concept of what I'm trying to do)
So in login I cannot do this.address to get the address because the address is held in each object. The login method is not technically part of the prototype. If it were, I wouldn't know how to call it from the HTML. (Well, that's not true, I would know how to call it, but I would only know how to call it as a prototype method, where it would execute the functionality but not have any of the local variables).
Any help with getting the login method that is called by myForm to know of the local variables would be greatly appreciated. The variable I want to get is this.address. The login function开发者_JAVA百科 is simply function login.
I think all you need to do is render the form to the document, lookup the button by the id and attach the event with attachEvent so you can control the scope.
this.loginBox = gDocument.createElement("loginBox");
this.loginBox.innerHTML = "<FORM name = 'myForm' action='' method='GET'><input type='text' name='usernameBox' id = 'usernameBox' VALUE=''><input type='password' id = 'passwordBox'><button type = 'button' value = 'Ok' id = 'loginButton'></FORM>"
// add this.loginBox to the document here
// Look up the button in the document and add the click handler
var button = gDocument.getElementById('loginButton');
button.attachEvent('onclick', this.login);
you may have to do something to bind the scope, can't remember.
var $this = this;
button.attachEvent('onclick', function() {
$this.login.apply($this, arguments);
});
Well, the "dirty" way is just passing the address to the function like this:
this.loginBox.innerHTML = "<FORM .... id = 'loginButton' onclick='login(\"" + this.address + "\");'>Login</button></FORM>";
The elegant way will be doing as Hemlock suggested but as I've no idea what is gDocument
I'm not sure it support the required methods.
精彩评论