使用onkeyup或键事件调用函数

时间:2017-03-23 15:23:02

标签: javascript

我想在input字段中按下(或释放)ENTER键时调用函数。我的旧代码有效,但问题是它在每个键上调用了函数,而不仅仅是ENTER键:

旧HTML:

<input class="halter"  type="text" onkeyup="checkLoesung(id);">

JS:

function checkLoesung(id){do stuff}

现在我尝试更改它,以便只有ENTER键触发该功能:

document.getElementsByClassName('halter').onkeypress = function(e){
    if (!e) e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == '13'){
        checkLoesung(id){do stuff}
      return false;
    }
  }

如果我从输入元素中删除onkeyup="checkLoesung(id);",这不应该有用吗?此处的问题是否与我尝试传递给函数的id相关联?

编辑:删除拼写错误 编辑2:完整代码:

<meta charset="UTF-8">
<div id="digger_cont">
<p id="ueberschrift_koth">King of the Hill</p>
<div id="fragen_halter">
<input id="ha_1" class="halter" placeholder="안녕하세요"  type="text" ><br/>
<input id="ha_2" class="halter" placeholder="얼굴" type="text" ><br/><br/>
<input id="ha_3" class="halter" placeholder="유방" type="text" ><br/><br/>
<input id="ha_4" class="halter" placeholder="물" type="text" ><br/><br/>
<input id="ha_5" class="halter" placeholder="병" type="text" ><br/><br/>
<input id="ha_6" class="halter" placeholder="책상" type="text" ><br/><br/>
<input id="ha_7" class="halter" placeholder="노래" type="text" >
</div>
<div id="score_halter">
<p>Punkte: <span id="score_not" style="display:none"></span></p>
<p id="melder"></p>
</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>

var l_count = 0; // Counter init, 0!
var last_sol = 7;  // ECHTE Anzahl an Luecken

document.getElementsByClassName('halter')[0].onkeypress = function(e){
    if (!e) e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == '13'){

        checkLoesung(id);
      return false;
    }
  }


function checkLoesung(id){
    if(l_count != last_sol) {

        var e_dies = document.getElementById(id).id;

        var LoesungArray = [
            "Hallo",
            "gesicht",
            "brust",
            "wasser",
            "flasche",
            "tisch",
            "lied"
            ];

        var score_not = document.getElementById('score_not');
        var punkt_score = (l_count + 1) * 3 + " / " + 3 * last_sol;

        // Meldungen
        var success_meldung = "richtig!";
        var fehler_meldung = "falsch!";
        var melde_mich = document.getElementById('melder');
        // String Formatierung
        var loe_strip = document.getElementById(e_dies).value.replace(/ /g,'');
        var loe_fin = loe_strip.toLowerCase();
        var array_fin = LoesungArray[l_count].toLowerCase();
                // Testen
        if (loe_fin == array_fin){
            melde_mich.innerHTML = success_meldung;
             $('#' + e_dies).nextAll('.halter:first').fadeIn('2000');
             $('#' + e_dies).nextAll('.halter:first').focus();

             l_count++;
             score_not.innerHTML = punkt_score;
                $('#score_not').css('display', 'none');
                $('#score_not').fadeTo('3000', 1);
                    // Bei letztem Durchgang
                    if(l_count == last_sol){
                            melde_mich.innerHTML = 'Richtig, du hast alles gelöst!';
                        return false;
                    };
            // Bei Leereingabe
            } else if(document.getElementById(e_dies).value == "") {
            melde_mich.innerHTML = '';
        }
            else {
            melde_mich.innerHTML = fehler_meldung;
                };

    } else {return false};
};
</script>

2 个答案:

答案 0 :(得分:1)

在if。

之外声明函数checkLoesung

还会将[0]索引添加到document.getElementsByClassName,因为它会返回一个集合

document.getElementsByClassName('halter')[0].onkeypress = function(e){
    if (!e) e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == '13'){
        
        console.log("Enter");
      return false;
    }
  }
  function checkLoesung(id){//do stuff
        }
<input class="halter"  type="text" onkeyup="checkLoesung(id);">

  

根据评论和更新的问题进行更新。

我向所有input添加了功能。因此,为此,请使用document.querySelectorAll并使用css查询。它返回一个数组。使用forEach并将addEventListener keypress添加到元素中。

  

阅读我发表的2条评论,并随心所欲。

代码如下。

var l_count = 0; 
var last_sol = 7;  

document.querySelectorAll('.halter').forEach(function(elem){
elem.addEventListener('keypress',function(e){
    if (!e) e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == '13'){
        //Key pressed is enter. Do whatever you want
        //console.log("Enter");
         alert('hello');
      return false;
    }
    //If required, add an else and add whatever you want when the key pressed is not enter
  });});


function checkLoesung(id){
    if(l_count != last_sol) {

        var e_dies = document.getElementById(id).id;

        var LoesungArray = [
            "Hallo",
            "gesicht",
            "brust",
            "wasser",
            "flasche",
            "tisch",
            "lied"
            ];

        var score_not = document.getElementById('score_not');
        var punkt_score = (l_count + 1) * 3 + " / " + 3 * last_sol;

    
        var success_meldung = "richtig!";
        var fehler_meldung = "falsch!";
        var melde_mich = document.getElementById('melder');
       
        var loe_strip = document.getElementById(e_dies).value.replace(/ /g,'');
        var loe_fin = loe_strip.toLowerCase();
        var array_fin = LoesungArray[l_count].toLowerCase();
               
        if (loe_fin == array_fin){
            melde_mich.innerHTML = success_meldung;
             $('#' + e_dies).nextAll('.halter:first').fadeIn('2000');
             $('#' + e_dies).nextAll('.halter:first').focus();

             l_count++;
             score_not.innerHTML = punkt_score;
                $('#score_not').css('display', 'none');
                $('#score_not').fadeTo('3000', 1);
                   
                    if(l_count == last_sol){
                            melde_mich.innerHTML = 'Richtig, du hast alles gelöst!';
                        return false;
                    };
            
            } else if(document.getElementById(e_dies).value == "") {
            melde_mich.innerHTML = '';
        }
            else {
            melde_mich.innerHTML = fehler_meldung;
                };

    } else {return false};
};
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="digger_cont">
<p id="ueberschrift_koth">King of the Hill</p>
<div id="fragen_halter">
<input id="ha_1" class="halter" placeholder="안녕하세요"  type="text" ><br/>
<input id="ha_2" class="halter" placeholder="얼굴" type="text" ><br/><br/>
<input id="ha_3" class="halter" placeholder="유방" type="text" ><br/><br/>
<input id="ha_4" class="halter" placeholder="물" type="text" ><br/><br/>
<input id="ha_5" class="halter" placeholder="병" type="text" ><br/><br/>
<input id="ha_6" class="halter" placeholder="책상" type="text" ><br/><br/>
<input id="ha_7" class="halter" placeholder="노래" type="text" >
</div>
<div id="score_halter">
<p>Punkte: <span id="score_not" style="display:none"></span></p>
<p id="melder"></p>
</div>

答案 1 :(得分:0)

使用getElementsByClassName访问元素时,它将返回数组。所以你应该使用它的索引

来访问它

您可以在此处plnkr

进行测试