javascript 如何将 onkeypress 事件附加到 Textarea

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

How to Attach onkeypress Event to a Textarea

javascripthtmlsmarty

提问by Abid Hussain

Question Update

问题更新

How should I check the condition of the ifstatement using onkeypress? I am using smartyand therefore need the {literal}tags.

我应该如何使用 来检查if语句的条件onkeypress?我正在使用smarty,因此需要{literal}标签。

{literal}
if(event.keyCode==13) {
  alert('hi');
}
{/literal}

Below is an example implementation.

下面是一个示例实现。

<textarea onkeypress="{literal} if(event.keyCode==13) {alert('hi');} {/literal}" class="fc_tab_txt"></textarea>

回答by larrylampco

You can do this, purely in javascript - without using jQuery, by creating your own function called SayHi()and putting it in the <head>section of your webpage. The function could have example implementation as follows:

您可以完全在 javascript 中执行此操作 - 无需使用 jQuery,只需创建您自己的调用函数SayHi()并将其放入<head>网页的某个部分即可。该函数可以具有如下示例实现:

{literal}
<script type="text/javascript">
<!--
  function isblank(field) {
    if (event.keyCode == 13) 
    {
        alert('hi');
    }
  }
// -->
</script>
{/literal}

You can call this function using the onkeypressevent as follows:

您可以使用onkeypress事件调用此函数,如下所示:

<textarea onkeypress="SayHi()" class="fc_tab_txt"></textarea>

<textarea onkeypress="SayHi()" class="fc_tab_txt"></textarea>

回答by Steven Liao

As Borgtex suggests, you should read up on the jQuery API. In general, this is how you attach event handlers using jQuery.

正如 Borgtex 建议的那样,您应该阅读 jQuery API。通常,这就是您使用 jQuery 附加事件处理程序的方式。

<script type="text/javascript" src="your jquery">
<script type="text/javascript">
    $("#text_area_id").keypress(function() {
        alert("I found Hogwarts.");
    });
</script>
<!-- random HTML stuffs -->
<textarea id="#text_area_id"></textarea>