-5

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

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>
4

1 回答 1

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();
于 2013-08-01T13:26:55.870 回答