2016-06-20 2 views
0

私は10のテキストボックスを持っていますが、私は5要素のonkeyとblurイベントを適用したいと思います。これをやった後onkeyupを適用し、JavaScriptによってテキストボックスにぼかしをかけます

for(var x=3;x<7;x++){ 
      document.getElementById("txt_"+x).onclick=function(){ 
      put_contents(document.getElementById("txt_"+x)); 
     }; 
      document.getElementById("txt_"+x).onkeyup = function(){ 
      validateHexa(document.getElementById("txt_"+x)); 
     }; 
      document.getElementById("txt_"+x).onblur = function(){ 
      restore_it(document.getElementById("txt_"+x)); 
     }; 
} 

私はそれがput_contentsは常にパラメータとして「txt_7」を服用しないでテキストボックスをクリックしてください。正しい方法を提案してください。ジャバスクリプトのみ

答えて

2

あなたがループ内(Notherの)閉鎖作成することで、xの値を「切り離す」ことができます。How do JavaScript closures work?

を参照してください、詳細については

for (var x = 3; x < 7; x++) { 
    (function(x) { 
     document.getElementById("txt_" + x).onclick = function() { 
      put_contents(document.getElementById("txt_" + x)); 
     }; 
     document.getElementById("txt_" + x).onkeyup = function() { 
      validateHexa(document.getElementById("txt_" + x)); 
     }; 
     document.getElementById("txt_" + x).onblur = function() { 
      restore_it(document.getElementById("txt_" + x)); 
     }; 
    })(x); 
} 

関連する問題