0
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

sqHTML = "<div id=\""+sqStringTemp+"\" class=\"puzzlesquare\"><input type=\"text\" class=\"puzzlesquareinput\" maxlength=\"1\" style=\"text-transform: uppercase;\" onkeypress=\"foo(event)\"/></div>";
jQuery("#gridpuzzleouter").append(sqHTML);

function foo(event) {
    //console.log(event.charCode);
    console.log( String.fromCharCode(event.charCode) );
}

//keydown event
jQuery(".puzzlesquareinput").on('keydown', function() {
    alert("keydown...");
});

我有一个奇怪的问题,事件没有触发。JavaScript 函数工作正常并将密钥打印到控制台。我想知道为什么 keydown 事件的 jQuery 没有触发。我的控制台中没有出现任何错误。jQuery 适用于 jsFiddle,但不适用于我的开发机器。

提前致谢...

4

2 回答 2

1

如果你有那个$(document).ready(), foo() 将是未定义的......试试这个......

更改此代码

function foo(event) {
        //console.log(event.charCode);
        console.log( String.fromCharCode(event.charCode) );
}

像这样的事情......

window.foo = function(event) {
    //console.log(event.charCode);
    console.log(String.fromCharCode(event.charCode));
}
于 2013-08-22T05:14:04.517 回答
0

jQuery(document).ready...当您将其包装在方法下时它将起作用。

$(document).ready(function () {
    sqHTML = "<input type=\"text\" class=\"puzzlesquareinput\" maxlength=\"1\" style=\"text-transform: uppercase;\" onkeypress=\"foo(event)\"/>";
    jQuery("body").append(sqHTML);

    foo = function (event) {
        //console.log(event.charCode);
        console.log(String.fromCharCode(event.charCode));
    }

    //keydown event
    jQuery(".puzzlesquareinput").on('keydown', function () {
        alert("keydown...");
    });
});

检查这个小提琴

于 2013-08-22T05:11:56.903 回答