javascript - 检测一个jsp中具有两个元素Id的输入事件

标签 javascript jquery

为什么警报只显示在最后一个事件上?我的目标是让所有输入事件都有效。谢谢。

这是我的代码:

$(document).off('keyup').on('keyup','#main',function(e){
    if(e.keyCode == 13) alert("enter on main input");
    });

    $(document).off('keyup').on('keyup','#other1',function(e){
    if(e.keyCode == 13) alert("enter on other input");
    });

看到这个FIDDLE用于演示

最佳答案

您在添加 keyup 处理程序后立即将其删除。实际上,这就是您现在正在做的事情......

$(document).off('keyup');

$(document).on('keyup','#main',function(e){
    if(e.keyCode == 13) alert("enter on main input");
});

$(document).off('keyup');  // this removes the event handler you just created

$(document).on('keyup','#other1',function(e){
    if(e.keyCode == 13) alert("enter on other input");
});

拆分代码,以便更清楚发生了什么,就像这样......

$(document).off('keyup');

$(document).on('keyup','#main',function(e){
    if(e.keyCode == 13) alert("enter on main input");
});

$(document).on('keyup','#other1',function(e){
    if(e.keyCode == 13) alert("enter on other input");
});

或者你可以像这样链接整个事情......

$(document)
    .off('keyup');
    .on('keyup','#main',function(e){
        if(e.keyCode == 13) alert("enter on main input");
    });
    .on('keyup','#other1',function(e){
        if(e.keyCode == 13) alert("enter on other input");
    });

这样做的优点是只需为文档创建一次 jQuery 对象,而不是像上面那样创建 3 次。

关于javascript - 检测一个jsp中具有两个元素Id的输入事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26584557/

相关文章:

javascript - 如何将鼠标跟踪效果添加到特定的 wordpress 行?

javascript - 如何刷新加载到现有 Javascript/jQuery 代码内的 Web 部件中的动态内容?

jquery - 使用 KnockoutJS 按日期对事件进行分组

javascript - 操作列中的所有字符串

javascript - 删除不在 jquery 中工作的父项

javascript - 如何在 Bing map v7 上创建自定义图钉

javascript - 将 Javascript 命名空间设置为 Window : Bad idea? 还是 Brilliant?

javascript - 每个,attr,还是这个?

javascript - 如何跳过 setInterval 函数的第一次延迟?

javascript - 甜蜜警报2 : Executing "function" or "async function" based on selection of a div after clicking a button