[英]Javascript: Getting ASCII code of last character in textarea
In my javascript program I am trying to display ASCII code of last character of TextArea. 在我的JavaScript程序中,我试图显示TextArea的最后一个字符的ASCII代码。 For that I am getting value of textArea, getting last character of text area and using charCodeAt(139) to get the code of last character but it's not working.
为此,我得到了textArea的值,获得了文本区域的最后一个字符,并使用charCodeAt(139)获得了最后一个字符的代码,但是它不起作用。 Can anyone tell me what's wrong in my code.
谁能告诉我我的代码有什么问题。
code: 码:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>signature</title>
<style>
#key{
color: #ffffff;
font-size: 20px;
text-align: center;
}
</style>
</head>
<body bgcolor="#3d382a">
<h2 style="color: #ffffff; text-align: center;"> MY MESSAGE </h2>
<form action="#" method="post">
<p style="text-align: center; color: #ffffff; font-size: 20px">
<textarea id="textarea" name="text" maxlength="140" rows="15" cols="40" ></textarea><br><br>
<span id="count"></span> characters</p><br>
<p id="key"> </p>
</form>
<script>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length) ;
var str = document.getElementById('textarea').value;
var lastChar = str.charAt(str.length - 1);
document.getElementById('key').innerHTML = "Last key in ASCII code: " + lastChar;
};
</script>
</body>
</html>
Change your last line. 更改最后一行。 Right now you just are logging the last character, whilst you need to get the ASCII code.
现在,您只需要记录最后一个字符,同时就需要获取ASCII码。
document.getElementById('key').innerHTML = "Last key in ASCII code: " + lastChar.charCodeAt(0);
var el_t = document.getElementById('textarea'); var length = el_t.getAttribute("maxlength"); var el_c = document.getElementById('count'); el_c.innerHTML = length; el_t.onkeyup = function () { document.getElementById('count').innerHTML = (length - this.value.length) ; var str = document.getElementById('textarea').value; var lastChar = str.charAt(str.length - 1); document.getElementById('key').innerHTML = "Last key in ASCII code: " + lastChar.charCodeAt(0); };
<h2 style="color: #ffffff; text-align: center;"> MY MESSAGE </h2> <form action="#" method="post"> <p style="text-align: center; color: #ffffff; font-size: 20px"> <textarea id="textarea" name="text" maxlength="140" rows="15" cols="40" ></textarea><br><br> <span id="count"></span> characters</p><br> <p id="key"> </p> </form>
Move your last three lines into your onkeyup function, this will update the #key element every time the input is updated. 将最后三行移动到onkeyup函数中,这将在每次输入更新时更新#key元素。 You also want to use str.length - 1 in the charCodeAt function, as you want to get the code for the last character, not just the 140th.
您还想在charCodeAt函数中使用str.length-1,因为您要获取最后一个字符的代码,而不仅仅是140个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.