按键事件仅触发一次

Keypress event firing only once

本文关键字:一次 事件      更新时间:2023-09-26

我是这样做的:

$(".classname").bind("keypress",function(){
    alert("event happened");
})

代码与上面类似,只工作一次,我的意思是,第一次你输入并单击 Enter 时,它正在工作,但下一次,它根本没有反应。

$("#id").bind("keypress",function(){
   alert("haiii");
}) 

第二个代码一直有效,但第一个代码只工作一次。

此外,如果第二个代码运行一次,则第一个代码甚至不会运行一次。

解决方案是什么?我想我这里缺少一些规则,你能告诉他们,以便我搜索它们吗?谢谢

事件绑定器应始终可用;如果不是,那是因为您正在更改 HTML 结构(追加或删除节点(。在您的情况下,您在运行时动态更改 HTML,您需要使用.on()

试试这个而不是.bind()

    $('#id').on({
       keypress: function () { alert("hi"); }
    });
    $('.ClassName').on({
       keypress: function () { alert("hi"); }
    });
    // IF YOU KNOW CLASSNAME ELEMENTS ARE INSIDE A FIXED ELEMENT:
    $('#FixedID').on({
       keypress: function () { alert("hi"); }
    }, '.ClassName');

关于编码风格,应将事件处理程序和处理事件的函数分开。例如,而不是处理程序也执行代码:

// one function that does everything!!
$(document).ready(function() {
    // bind events
    $('#SomeID').on({
       click: function () {
         // huge wall of code that handles events
       },
       mouseenter: function () {
         // another huuuuuuuge wall of code here
       }
    )};
});

你应该有这样的东西:

$(document).ready(function () {
    BindHandlers();
    DoSomethingElseWithPageInit();
}); 
function BindHandlers() {
// handlers do just the handling of events; easy to see and understand
   $('#SomeID').on({
      click: function (e) { ClickOnSomeID(e); },
      mouseenter: function () { MouseEnterOnSomeID(); }
   )};
}
// here are the functions that process the event
function ClickOnSomeID(e) { ... }
function MouseEnterOnSomeID() { ... }

正如Frenchie所指出的,这是因为你的html结构发生了变化。这已经被 .live(( 处理了,但现在 .on(( 是继任者。但是你应该在元素上使用 on((,而不是在文档上:

$(document).on("keypress", "#id", function(){
alert("event happened");
})