Jquery onfocus无法正常工作

时间:2014-11-07 18:19:35

标签: javascript jquery

我有一个文本区域,我正在尝试根据空格键何时命中运行一个函数。但是,代码不起作用,我似乎无法弄清楚原因。从我做过的研究看起来是正确的。

这是文本区域定义:

<div class="DivWithScroll" id="my_text" contenteditable="true" onkeypress="return myKeyPress(event)" onkeydown="return onKeyDown(event)">

到目前为止,我在页面上的Jquery代码试图运行.onFocus()

$('document').ready(function () {
        $('#my_text').focus(function () {
            $('#my_text').keydown(function (e) {
                if (e.keyCode == '32') {
                    alert('space');
                }
            });
            alert("Focused!");
        });
    });

1 个答案:

答案 0 :(得分:2)

这是因为你正在使用警报。 Stop using alert for troubleshooting

这有效 -

$('#my_text').focus(function () {
    $('#my_text').keyup(function (e) {
        if (e.keyCode == '32') {
            console.log('space');
        }
    });
    console.log("Focused!");
});

在这种情况下使用keyup()可能会更好,以避免在按下按键时出现问题。 example