简体   繁体   English

Keypress 事件只触发一次

[英]Keypress event firing only once

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谢谢

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).如果不是,那是因为您正在更改 HTML 结构(添加或删除节点)。 In your case, you're dynamically changing HTML at runtime, you need to use .on()在您的情况下,您在运行时动态更改 HTML,您需要使用.on()

Try this instead of .bind() :试试这个而不是.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() { ... }

As frenchie notes, it's because your html structure has changed.正如法国人所说,这是因为您的 html 结构发生了变化。 This has been treated right by .live(), but now .on() is the successor.这已被 .live() 正确处理,但现在 .on() 是继任者。 But you should use on() not on the element, but on the document:但是你不应该在元素上使用 on() ,而应该在文档上使用:

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

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

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