简体   繁体   English

JavaScript:当onFocus在此代码中工作时,为什么onKeyDown和onKeyUp不起作用

[英]JavaScript: Why onKeyDown and onKeyUp don't work while onFocus is working in this code

function PrepareCounter() {
    var ct = 1;
    while(document.getElementById("id_answer"+ct)) {
        document.getElementById("id_answer"+ct).setAttribute("onFocus", "countChars('textbox','char_count',140)", "onKeyDown", "countChars('textbox','char_count',140)", "onKeyUp", "countChars('textbox','char_count',140)");
        ct += 1;
    }
}

If i focus my element countChars is executed but if i write something it's not. 如果我关注我的元素countChars被执行但如果我写了一些东西它不是。

setAttribute only takes 2 arguments, you would have to call each of those separately. setAttribute只接受2个参数,你必须分别调用每个参数。

Rather than using strings, you can use real functions: 您可以使用实际函数,而不是使用字符串:

function PrepareCounter() {
    var ct = 1;
    var elem;
    while (elem = document.getElementById("id_answer" + ct)) {
        elem.onfocus = elem.onkeydown = elem.onkeyup = function() {
            countChars('textbox', 'char_count', 140);
        };
        ct += 1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM