Javascript jquery keyup 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12290019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:37:19  来源:igfitidea点击:

jquery keyup not working

javascriptjquery

提问by 1252748

For some reason, when I add a class to various inputs (after a user presses submit), this function does not record keypresses being made within those inputs. I must be doing something fundamentally wrong as I've tried $('incomplete_required').keyup(){}and what is below, as it seems .on()is more modern..

出于某种原因,当我向各种输入添加一个类时(在用户按下提交后),此函数不会记录在这些输入中进行的按键操作。我一定是在做一些根本错误的事情,因为我已经尝试过$('incomplete_required').keyup(){}以及下面的内容,因为它似乎.on()更现代..

$(document).ready(function(){
    $('.incomplete_required').on("keyup", function(){
        console.log('keyed');
    });
});

What have I done wrong here?

我在这里做错了什么?

Thank you

谢谢

回答by ?????

If you are dynamically changing elements in the dom - it is best to delegate the event to an existing parent in the dom

如果您正在动态更改 dom 中的元素 - 最好将事件委托给 dom 中的现有父级

$(document).ready(function(){
    $('body').on("keyup",'.incomplete_required', function(){
        console.log('keyed');
    });
});

Obviously replacing bodywith the closest parent element that exists on dom ready

显然替换body为 dom ready 上存在的最近的父元素

By delegating - the event will bubble up to the "parent" element - which is where the event is handled

通过委托 - 事件将冒泡到“父”元素 - 这是处理事件的地方

回答by Nope

Seeing this works before the submit I think you are loosing the event bindings as the elements are re-rendered but the document ready event is not firing again.

在提交之前看到这有效,我认为您正在失去事件绑定,因为元素被重新渲染,但文档就绪事件不会再次触发。

A dynamic binding solution may be required here:

这里可能需要动态绑定解决方案:

$(document).ready(function(){
    $(document).on('keyup', '.incomplete_required', function(){
        console.log('keyed');
    });
});?

Mind you, documentis very far up so the closest static element will be better off course.

请注意,document距离很远,因此最接近的静态元素当然会更好。

回答by arhea

Bind to the "keypress" event instead.

改为绑定到“keypress”事件。

Edit: http://jsfiddle.net/RRgvU/

编辑:http: //jsfiddle.net/RRgvU/