繁体   English   中英

jQuery文档已准备就绪,并按键可以调用一个函数

[英]jQuery document ready and keypress to call one function

我试图将其作为文档准备好功能,当按下Enter键时触发该功能,但我不断收到错误消息“ enableEnter未定义”。

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

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

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

$(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();
    }
}

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

  $(document).ready(function() {

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

});

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

暂无
暂无

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

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