按键事件仅触发一次 [英] Keypress event firing only once

查看:201
本文介绍了按键事件仅触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这样做:

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

类似于上面的代码,仅工作一次,我的意思是,第一次键入并单击Enter时,它是有效的,但是下一次,它根本没有反应.

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

推荐答案

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

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()

尝试使用此方法代替.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() { ... }

这篇关于按键事件仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆