【问题标题】:Unable to detect "Enter key" in Javascript with Php无法使用 PHP 检测 Javascript 中的“输入键”
【发布时间】:2022-02-01 19:26:50
【问题描述】:

我正在使用 php 和 javascript,我有 texarea,每当我输入任何文本和 按“Enter键”然后应该显示警报,但现在文本将转到下一行而不是显示警报框,

这是我的html代码

<textarea  placeholder="Write a comment1…" id="txt'.$FeedId.'" rows="1" class="reply_post_new" style="overflow:hidden" onkeypress="return Addcomment1(this)"></textarea>

这是我的脚本代码,我哪里错了?

<script>
function Addcomment1(e) {
    f (e.keyCode == 13) {
        alert('Hello world');
        return false;
    }
}
</script>

【问题讨论】:

    标签: javascript php html jquery


    【解决方案1】:

    问题的原因是您将 textarea 元素传递给函数而不是事件对象。

    您的其他问题是您使用的是内在事件属性(带有一堆陷阱)和已弃用的 keyCode 属性。您还打错字和拼写错误if。最后,以大写字母开头的函数名称传统上是为构造函数保留的,而您的则不是。

    const textarea = document.querySelector('textarea');
    textarea.addEventListener('keypress', addComment1);
    
    function addComment1(e) {
      if (e.key === "Enter") {
        alert('Hello world');
        e.preventDefault();
      }
    }
    &lt;textarea placeholder="Write a comment1…" id="txt'.$FeedId.'" rows="1" class="reply_post_new" style="overflow:hidden"&gt;&lt;/textarea&gt;

    除此之外,由于您有一行 &lt;textarea&gt; 阻止使用 Enter 键……您可能应该摆脱 JS 并改用 &lt;input type="text&gt;

    【讨论】:

    • 我在同一页面中有两个不同的文本框,那么我该如何管理两个文本区域?
    • 给他们每个人打电话addEventListener
    • 你的意思是“document.querySelector('#your id ');”对吗?
    • 这是一种选择。我可能会给他们类名,然后循环执行。
    • 如何在循环中获取 "document.querySelector("#your id"); "值?
    【解决方案2】:

    函数Addcomment1(this)中的参数this返回元素本身,而不是您希望获取的键事件,因此您必须使用javascript addEventListener获取事件键并使用key而不是@987654325 @ 因为它是一个已弃用的属性

    HTML:

    <textarea placeholder="Write a comment1…" id="txt'.$FeedId.'" rows="1" class="reply_post_new" style="overflow:hidden"></textarea>
    

    JS:

    let textarea = document.querySelector('.reply_post_new');
    
    textarea.addEventListener('keypress', function(e) {
        if(e.keyCode == 13) {
            alert('Hello world');
            return false;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 2015-02-16
      • 2012-08-21
      • 2013-07-22
      • 1970-01-01
      相关资源
      最近更新 更多