Keypress event firing only once

时间秒杀一切 提交于 2019-12-13 02:22:12

问题


I am doing like this :

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

code similar to above, working only once, I mean, the first time you type and click enter, it's working, but next time, its not at all reacting.

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

the second code working all the time, but the first code working only once.

Also if second code is run once, the first code is not even running once.

What is the solution? I think I am missing some rules here, can you tell them so that I will search about them. Thanks


回答1:


The event binder should be always available; if it's not it's because you're changing the HTML structure (either appending or deleting nodes). In your case, you're dynamically changing HTML at runtime, you need to use .on()

Try this instead of .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');

Regarding your coding style, you should separate the event handlers and the functions that handle the events. For instance, instead of this where the handlers also execute code:

// 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
       }
    )};
});

You should have something like this:

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



回答2:


As frenchie notes, it's because your html structure has changed. This has been treated right by .live(), but now .on() is the successor. But you should use on() not on the element, but on the document:

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


来源:https://stackoverflow.com/questions/10689686/keypress-event-firing-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!