我如何使用EJS文件中的onkeypress-events调用函数?

问题描述 投票:0回答:1

我正在尝试为文本输入字段完成实时字符计数器,但似乎无法使其正常工作。 onkeypress函数要么未定义,要么在加载页面时被调用一次]

仅用onkeypress =“”分配功能似乎不起作用。

此外,我想更新charcountLabel的文本;我似乎无法做到。简单地使用'document.getElementById'更新其innerHTML无效。

  1. 我如何正确地为.ejs中的html元素分配按键功能?
  2. 我如何访问和更新其他元素的innerHTML?

请参见下面的代码:

    <input type="text" id="textContent" onkeypress="charcount">

    // Should be live-updated with the length of input text above.
    <span id="charcountLabel"> 0 </span> 

    <script>    
        function charcount() {
            var characterCount = document.getElementById("textContent").innerText.length;
            document.getElementById("charcountLabel").innerHTML = characterCount;
        }
    </script>
javascript ejs live onkeypress
1个回答
0
投票

您在这里

<input type="text" id="textContent" onkeypress="charcount()">

<!-- Should be live-updated with the length of input text above. -->
<span id="charcountLabel">0</span> 
<script>
    function charcount() {
        var characterCount = document.getElementById("textContent").value.length;
        document.getElementById("charcountLabel").innerHTML = characterCount;
    }
</script>

使用括号()调用该函数,并将innerText替换为value属性。请注意,//在Javascript中是注释,而不是在HTML中应使用<!-- your comment -->的注释。最后,它与ejs无关。

© www.soinside.com 2019 - 2024. All rights reserved.