从HTML创建对象和调用JavaScript方法

Creating objects and calling JavaScript methods from HTML

本文关键字:JavaScript 方法 调用 HTML 创建对象      更新时间:2023-09-26

我对JavaScript不是很熟悉,我对它的面向对象特性有点困惑。我正在尝试使用JavaScript中的对象、方法和属性的概念创建凯撒转换。我使用HTML表单从用户和OnClick返回编码的密文给用户输入。这是我有的。我很确定我的逻辑,但我猜我的对象创建和方法调用失败了。我做得对吗?任何帮助都是感激的。谢谢!

    <head>
    <script>
    function Caesar(order){
    this.order = order;
    this.encode = encode;
    function encode(input){
    this.output = '';
    for (var i = 0; i < input.length; i++) {
    var this.c = input.charCodeAt(i);
    if      (this.c >= 65 && this.c <=  90) this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65);  // Uppercase
    else if (this.c >= 97 && this.c <= 122) this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97);  // Lowercase
    else   this.output += input.charAt(i);    
    }
    return answer.innerHTML= output;
     } 
    </script></head>
    <body>
    <form>
    Enter Plaintext : <input type = "text" name = "plaintext"> 
    Enter Shift:      <input type = "text" name = "shift"><br> --How do I get the input from here and create my caesar object?
    <input type="button" value="Encode" onclick ="encode()"> --How do I call the encode() method with input from the plaintext text box?  
    </form>
    </body></html>

为纯文本框指定一个id,通过该id,您可以在JavaScript中接收它的值。

<input type="text" name="plaintext" id="plain_text">

在JavaScript中,使用document.getElementById(element_name):

获取HTML元素

var plainTextBox = document.getElementById('plain_text');

从文本框中检索值就像:

plainTextBox.value