<script src ="a.js" ></script>
<script language="javascript">
function bandInput()
{
var control = document.getElementById("txtUserName");
var checker = new Check();
checker.band(control);
}
</script>
//然后再body的onload事件里面调用bandInput(),当触发txtUserName的onchange事件时,提示错误:对象不支持此方法。a.js代码:
function Check(){
this.pass = true ;
this.checkInput() = function(control)
{
if(typeof(control.value)=="undifined"||control.value==null)
{
this.pass = false;
}
}
this.band = function(control)
{
document.form1.onsubmit = function()
{
//不管验证是否通过,return 的都是true;
return this.pass;
}
control.onchange = function()
{
//错误就在这一行,提示对象不支持方法;
this.checkInput(control);
}
}
}
我觉得大概和面向对象应的问题该有些关系。
如上面band函数的代码改成
control.onchange = function()
{
//错误就在这一行,提示对象不支持方法;
this.checkInput(control);
}为:
control.onchange = function()
{
if(typeof(control.value)=="undifined"||control.value==null)
{
this.pass = false;
}
}
//则此行可以通过,但是onsubmit始终还是true,是在是挠头啊。应该怎么解决上诉问题,
改成
this.checkInput = function(control)
function Check(){
//var me=this;这里定义也没有问题
this.pass = true ;
this.checkInput() = function(control)
{
if(typeof(control.value)=="undifined"||control.value==null)
{
this.pass = false;
}
}
this.band = function(control)
{
var me=this;
document.form1.onsubmit = function()
{
//不管验证是否通过,return 的都是true;
return this.pass;
}
control.onchange = function()
{
//错误就在这一行,提示对象不支持方法;
me.checkInput(control);
}
}
}因为你是函数嵌套了几层,那么this的指向就会发生改变,不是指向Check()了,所以找不到对应的方法。
所以在外层把指向Check()的this赋值一下。你看看submit一直为true是不是这个问题。不是的话就是判断错误。
<input type="text" id = "txtUserName">
<input type="submit" value="检测">
</form>
<script language="javascript">
function Check(){
this.pass = true;
this.checkInput = function(control)
{
alert(1);
// if(typeof(control.value)=="undifined"||control.value==null||control.value=="")
// {
// this.pass = false;
// }
}
this.band = function(control)
{
document.form1.onsubmit = function()
{
return false;
}
control.onchange = function()
{
this.checkInput(control);//此处的this不再是父类对象了,而是onchange所触发的这个本函数了
}
}
}window.onload = function bandInput()
{
var control = document.getElementById("txtUserName");
var checker = new Check();
checker.band(control);
}</script>
<form id="form1" name="form1" action="ad.php" method="post">
<input type="text" id = "txtUserName">
<input type="submit" value="检测">
</form>
<script language="javascript">
function Check(){
var t = this, pass = false;
t.checkInput = function(control)
{
if(typeof(control.value)=="undifined"||control.value==null||control.value==""){
pass = false;
}else{
pass = true;
}
}
t.band = function(control)
{
document.form1.onsubmit = function()
{
return pass;
}
control.onchange = function()
{
t.checkInput(control);
}
}
}window.onload = function bandInput()
{
var control = document.getElementById("txtUserName");
var checker = new Check();
checker.band(control);
}</script>
control.onchange = function()
{
//错误就在这一行,提示对象不支持方法;
this.checkInput(control);
}
这里的this指的是control这个对象,control这个对象没有那个方法了