在innerHTML调用的Javascript函数中调用它

时间:2011-01-03 19:55:52

标签: javascript html dom

我正在创建Windows 7小工具并允许用户通过小工具登录。小工具将登录到用户提供的任何有效(由应用程序域定义)地址。现在,我遇到了一个问题。我做这样的事情:

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>";

(注意:如果有人可以格式化上面那些很好的代码,但是没有必要确切地知道我正在做什么,只是为了知道我试图做的事情的概念)

所以在登录时我不能这样做。地址获取地址,因为地址保存在每个对象中。登录方法在技术上不是原型的一部分。如果是的话,我不知道如何从HTML中调用它。 (嗯,那不是真的,我会知道如何调用它,但我只知道如何将其称为原型方法,它将执行功能但不具有任何局部变量)。 / p>

任何有关获取myForm调用的登录方法以了解局部变量的帮助都将非常感激。我想得到的变量是this.address。登录功能只是登录功能。

2 个答案:

答案 0 :(得分:0)

我认为您需要做的就是将表单呈现给文档,通过id查找按钮并使用attachEvent附加事件,以便您可以控制范围。

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);

你可能要做一些事情来绑定范围,不记得了。

var $this = this;
button.attachEvent('onclick', function() {
  $this.login.apply($this, arguments);
});

答案 1 :(得分:0)

嗯,“脏”方式只是将地址传递给函数,如下所示:

this.loginBox.innerHTML = "<FORM ....  id = 'loginButton' onclick='login(\"" + this.address + "\");'>Login</button></FORM>";

优雅的方式将像Hemlock建议的那样,但我不知道什么是gDocument我不确定它是否支持所需的方法。