空错误在javascript中出现

时间:2013-08-01 13:18:44

标签: javascript oop

我在javascript对象的属性中为keyup事件赋值。它在控制台中打印为空。

function check(id){
    var me= this;
    this.ID= null;
    this.matchName= this.ID.substr(this.ID.lastIndexOf('_'));
    this.first= function (){
    alert(me.matchName)
}

this.second= function (){
    alert(1)
}

this.touch= function (){
    $(id).find('input').keyup(function(e){
    me.ID= this.id;;
    if(e.keyCode==13){
        id.indexOf('first')>-1? me.first(): me.second();
    }
    })} 
}

<div class="first">
    <input type="text" id="val_00_01" />
</div>
<div class="two">
    <input type="text" id="val_00_02"/>
</div>
<script type="text/javascript">
    var first= new check('.first');
    var two= new check('.two');
    first.touch()
    two.touch()
</script>

1 个答案:

答案 0 :(得分:1)

这是一个破碎的部分(除非它是故意的?)

将ID属性设置为null

this.ID= null;

尝试访问刚设置的属性等于null

this.matchName= this.ID.substr(this.ID.lastIndexOf('_'));

此代码在Check类的初始化(构造函数)中运行,并且会出错。


这就是我认为你想要的,更好的格式化,以免导致眼睛流血。

// capitalize first letter of class name
function Check(className){ // use a prop/descriptive parameter name 
    var me = this; // set your variable "me" to class instanced
    this.ID = null; // INITIALIZE your ID and matchName variables
    this.matchName = null;

    this.first = function (){
        alert(me.matchName)
    };
    this.second = function (){
        alert(1)
    };
    this.touch = function (){
        // get the element with class=className
        // find the input inside of it
        // set an onkeyup handler to the input element
        $(className).find('input').keyup(function(e){
            me.ID = this.id;; // set the ID variable to the INPUT element's ID property
            // set matchName to the last part of the input's ID property
            // matchName will be "01" or "02" in this case
            me.matchName = this.ID.split("_")[this.ID.split("_").length - 1];
            if(e.keyCode==13){
                id.indexOf('first') > -1 ? me.first(): me.second();
            }
        });
    };
}
...
var first = new Check('.first');
var two = new Check('.two');
first.touch();
two.touch();