我正在尝试创建一个 jQuery 类来在提交表单时验证输入字段。我在同一个页面中有不同的表单,我需要为每个表单创建一个验证器实例。
HTML
<form method="post" action="index.php" id="form1">
<input type="submit" value="Send" />
</form>
<form method="post" action="index.php" id="form2">
<input type="submit" value="Send" />
</form>
<script type="text/javascript">
var form1 = new DataValidator('#form1');
var form2 = new DataValidator('#form2');
</script>
我会从提交事件处理程序访问对象变量,但是当我打印 this.selector
变量时,我看到一个 undefined
值。
JavaScript
function DataValidator(selector)
{
this.form = $(selector);
this.selector = selector;
$(selector).submit(function()
{
alert('submit ' + this.selector);
return false;
});
}
最佳答案
this
不是局部变量,因此它不会保存在闭包中。您需要将其保存在局部变量中。在 jQuery 事件处理程序中,this
始终绑定(bind)到事件的目标。
function DataValidator(selector)
{
this.form = $(selector);
this.selector = selector;
var self = this;
this.form.submit(function()
{
alert('submit ' + self.selector);
return false;
});
}
关于javascript - 从javascript对象中的事件处理程序访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23929791/