如何在javascript中将char转换为ascii

how to convert char to ascii in javascript

本文关键字:转换 ascii char 中将 javascript      更新时间:2023-09-26

我想知道如何让这段代码工作,因为目前它不工作。我应该得到字符串,它应该把它转换成ASCII。我有两个带有输入和输出结果的文本框,还有一个按钮进行转换。非常感谢你的帮助!!!

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Convert to ASCII</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter your mail:
        <input TextBox ID="TextBox1" runat="server"     ontextchanged="TextBox1_TextChanged"><TextBox/>
</p>
        <Button type="Button" onclick="Ascii()">Convert to ASCII</button>
</p>
        Output:
        <input TextBox ID="TextBox2" runat="server"     ontextchanged="TextBox2_TextChanged"><TextBox/>
</p>
<p>
<script>
        function Ascii() {
        textbox2 = String.charCodeAt(TextBox1);
           }
         </script>
       </p>
    </form>
</body>
</html>

使用charCodeAt() javascript函数

已经提到它是javascript函数

您可以使用

  1. 从字符到ASCII

    charCodeAt();

  2. 从ASCII到字符:

    String.fromCharCode()

TextBox1和TextBox2是整个对象。指定值并在字符上循环

function Ascii() {
    var ascii = "";
    for (var i = 0, len = TextBox1.value.length; i < len; i++) {
      ascii = ascii + TextBox1.value.charCodeAt(i);
    }
    TextBox2.value = ascii;
}

尝试使用以下方式。。。

 <div>
    Enter your mail:
    <input TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"><TextBox/>
 </div>
 <div>
 <Button type="Button" onclick="Ascii('TextBox1')">Convert to ASCII</button>
 </div>
 <div>
    Output:
    <input TextBox ID="TextBox2" runat="server"     ontextchanged="TextBox2_TextChanged"><TextBox/>
</div>
 <script type="text/javascript">
    function Ascii(TextBox1) 
    {
        var val = document.getElementById(TextBox1).value;
        alert(val.charCodeAt(0));
        document.getElementById('TextBox2').value = val.charCodeAt(0);
    }
   function StringToAscii(TextBox1) 
    {
        var val = document.getElementById(TextBox1).value;
        for(var i = 0; i < val.length; i++) {
            document.getElementById('TextBox2').value += val.charCodeAt(i);
        }
    }
</script>

所以使用.charCodeAt(0),您将获得ascii值。。。