jQuery 如何使用jquery触发输入事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17678161/
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-26 19:43:32  来源:igfitidea点击:

How to trigger enter event with jquery

jquery

提问by dzumla011

I have the following which works:

我有以下工作:

$('textarea').keypress(function(e) {
    if (e.keyCode == '13') {
        alert('code');
    }
});

But I want to trigger that same thing when the page loads, I tried the following but it doesn't work:

但是我想在页面加载时触发同样的事情,我尝试了以下但它不起作用:

var e = jQuery.Event("keypress");
e.which = 13; // Enter
$('textarea').trigger(e);

NOTE: I want to have the first snipped of code there, I DO NOT want to remove it.

注意:我想在那里剪下第一个代码,我不想删除它。

回答by Chirag Vidani

Use "which" instead of keyCode. "Which" works in both scenario

使用“which”而不是keyCode。“哪个”适用于两种情况

$('textarea').keypress(function (e) {
    if (e.which == '13') {
        alert('code');
    }
});

回答by Dima Kuzmich

Here is a solution for your problem http://jsfiddle.net/dima_k/zPv2a/

这是您的问题的解决方案http://jsfiddle.net/dima_k/zPv2a/

$('button').click(function(){
    debugger
    var e = $.Event("keypress");
    e.keyCode = 13; // # Some key code value
    $('#textbox').trigger(e);
});

 $('#textbox').keypress(function(e)
 {
    if (e.keyCode == '13') {
        alert('code');
    }
});

回答by karaxuna

Alternative solution:

替代解决方案:

var textarea = $('textarea').keypress(OnTextareaKeypress);
$(function(){
    OnTextareaKeypress.call(textarea[0], { e: { which: 13 } });
});

function OnTextareaKeypress(e) {
    if (e.which == '13') {
        alert('code');
    }
}