Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - 如何在EJS文件中使用onkeypress-events调用函数?(How can I call functions using onkeypress-events in EJS file?)

I'm trying to accomplish a live character counter for a text input field, but cannot seem to make it work.

(我正在尝试为文本输入字段完成实时字符计数器,但似乎无法使其正常工作。)

The onkeypress-function either go as undefined or is just called once when loading the page

(onkeypress函数要么未定义,要么在加载页面时被调用一次)

Simply assigning the function with onkeypress=" " does not seem to work.

(仅使用onkeypress =“”分配功能似乎无效。)

Additionally, I want to update the text of charcountLabel;

(另外,我想更新charcountLabel的文本。)

which I cannot seem to do.

(我似乎无法做到。)

Simply using ' document.getElementById ' for updating its innerHTML does not work.

(简单地使用' document.getElementById '来更新其innerHTML无效。)

  1. How do I correctly assign keypress-functions to html-elements in .ejs?

    (如何正确地将keypress-functions分配给.ejs中的html-elements?)

  2. How do I access and update innerHTML of other elements?

    (如何访问和更新其他元素的innerHTML?)

See code below:

(参见下面的代码:)

    <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>
  ask by B. Ginner translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you are

(这个给你)

<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>

Use parenthesis () to call the function and replace innerText with value property.

(使用括号()来调用该函数,并将innerText替换为value属性。)


Note that // is comment in Javascript, not in html where you should use

(请注意//是Javascript中的注释,而不是应使用HTML的注释)


<!-- your comment --> instead.

(<!-- your comment -->代替。)



Last, it has nothing to do with ejs.

(最后,它与ejs无关。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...