jQuery文件就绪和按键调用一个函数

时间:2014-06-25 14:41:26

标签: javascript jquery

我试图将此作为文档就绪函数,在按下回车键时触发,但我不断收到错误消息" enableEnter未定义"。

    $(document).ready(enableEnter());

    $('#formPartOverride').keypress(function enableEnter(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            ezpConsole.partOverride.retrieveParts();
        }
    });

2 个答案:

答案 0 :(得分:3)

这是实现这一目标的正确方法:

$(document).ready(function () {
    // When the DOM is ready, attach the event handler.
    $('#formPartOverride').keypress(function (event) {            
        enableEnter(event);
    });
});

// enableEnter is accessible in the whole page scope.
function enableEnter(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
        ezpConsole.partOverride.retrieveParts();
    }
}

Example

答案 1 :(得分:0)

enableEnter() keypress keypress1 function - it is only defined in the scope of the $(document).ready()`函数之外创建函数function, so will not be available to anything above that specific scope. You could encase the entire script inside the,例如:

  $(document).ready(function() {

    $('#formPartOverride').keypress(function enableEnter(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            ezpConsole.partOverride.retrieveParts();
        }
    });

});

这将等到文档准备好使附带的脚本可用。