2013-08-01 2 views
-5

Я назначаю значение для события keyup в свойстве объекта javascript. Он печатает нуль в консоли.Ошибка Null в javascript

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> 
+3

Вы забыли задать вопрос и форматировать свой код. – MightyPork

+1

Вы не привели нам пример того, где код разбивается или в каком сценарии, когда он работает. – NoLifeKing

ответ

1

Ну это одна сломана часть (если это не намеренно?)

Установите свойство ID обнулить

this.ID= null; 

Попробовать получить доступ к свойству вы просто установлен равным нулю

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

Этот код работает в инициализации (конструкторе) вашего класса проверки и будет выходить из строя.


Вот что я думаю, что вы хотите, с более форматирования так, чтобы не вызвать глазное кровотечение.

// 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(); 
+0

Когда я нажимаю клавишу ввода, тогда он должен заполнять идентификатор – Carlos

+0

@amit. Какая магия изменит его, когда вы измените его на нуль и попытаетесь использовать его в следующей строке? – JJJ

+0

@lastCoder: событие onkeyup me.ID = this.id; – Carlos

Смежные вопросы