【问题标题】:How do I make a javascript function a html attribute?如何使 javascript 函数成为 html 属性?
【发布时间】:2020-07-20 11:26:09
【问题描述】:

我有一个带参数的 javascript 变量,但我不知道如何将它传递到我的 html 代码中。 javascript代码取自https://gist.github.com/EvanHahn/2587465

var caesarShift = function(str, amount) {

    // Wrap the amount
    if (amount < 0)
        return caesarShift(str, amount + 26);

    // Make an output variable
    var output = '';

    // Go through each character
    for (var i = 0; i < str.length; i ++) {

        // Get the character we'll be appending
        var c = str[i];

        // If it's a letter...
        if (c.match(/[a-z]/i)) {

            // Get its code
            var code = str.charCodeAt(i);

            // Uppercase letters
            if ((code >= 65) && (code <= 90))
                c = String.fromCharCode(((code - 65 + amount) % 26) + 65);

            // Lowercase letters
            else if ((code >= 97) && (code <= 122))
                c = String.fromCharCode(((code - 97 + amount) % 26) + 97);

        }

        // Append
        output += c;

    }

    // All done!
    return output;

};

显然我想将它传递给我的 HTML。我做了一些研究,并遇到了以下方法:

&lt;p id="output"&gt;&lt;/p&gt;

然后

document.getElementById('output').innerHTML = lengthOfName;

但我不知道如何将它们加在一起。如何调用变量?对于字符串,我有一个文本区域输入框,也许还有第二个参数的点击器,金额,但我不知道如何将它们放在 HTML 中。

【问题讨论】:

    标签: javascript html encryption caesar-cipher


    【解决方案1】:

    您需要在 html 文档的 body 中添加 script 标记内的 JavaScript 和 id 获得的 p 标记,如下所示:

    <!DOCTYPE html>
    
    <html>
      <head>
        <title>Page</title>
      </head>
    
      <body>
        <form id="form">
          <div>
            <label for="str">String:</label>
            <input id="str" />
          </div>
          <div>
            <label for="amount">Amount:</label>
            <input id="amount" />
          </div>
          <button type="submit">Submit</button>
        </form>
        <p>CaesarShift: <span id="output"></span></p>
    
        <script>
          var caesarShift = function (str, amount) {
            // Wrap the amount
            if (amount < 0) return caesarShift(str, amount + 26);
    
            // Make an output variable
            var output = "";
    
            // Go through each character
            for (var i = 0; i < str.length; i++) {
              // Get the character we'll be appending
              var c = str[i];
    
              // If it's a letter...
              if (c.match(/[a-z]/i)) {
                // Get its code
                var code = str.charCodeAt(i);
    
                // Uppercase letters
                if (code >= 65 && code <= 90)
                  c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
                // Lowercase letters
                else if (code >= 97 && code <= 122)
                  c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
              }
    
              // Append
              output += c;
            }
    
            // All done!
            return output;
          };
    
          const form = document.getElementById("form");
          form.addEventListener("submit", handleSubmit);
    
          function handleSubmit(event) {
            event.preventDefault();
            let str = document.getElementById("str").value;
            let amount = parseInt(document.getElementById("amount").value);
            let output = document.getElementById("output");
            console.log(amount);
            if (!amount) {
              output.innerHTML = `<span style="color: red">Amount not valid</span>`;
              return;
            }
            output.innerHTML = caesarShift(str, parseInt(amount));
          }
        </script>
      </body>
    </html>
    

    请参阅下面的 sn-p 示例:

    var caesarShift = function(str, amount) {
      // Wrap the amount
      if (amount < 0) return caesarShift(str, amount + 26);
    
      // Make an output variable
      var output = "";
    
      // Go through each character
      for (var i = 0; i < str.length; i++) {
        // Get the character we'll be appending
        var c = str[i];
    
        // If it's a letter...
        if (c.match(/[a-z]/i)) {
          // Get its code
          var code = str.charCodeAt(i);
    
          // Uppercase letters
          if (code >= 65 && code <= 90)
            c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
          // Lowercase letters
          else if (code >= 97 && code <= 122)
            c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
        }
    
        // Append
        output += c;
      }
    
      // All done!
      return output;
    };
    
    const handleSubmit = (e) => e.preventDefault();
    
    const updateResult = () => {
      amount = parseInt(document.getElementById("amount").value);
      let output = document.getElementById("output");
      if (!amount) {
        output.innerHTML = `<span style="color: red">Amount not valid</span>`;
        return;
      }
      output.innerHTML = caesarShift(
        document.getElementById("text").value,
        parseInt(amount)
      );
    };
    
    const form = document.getElementById("form");
    form.addEventListener("submit", handleSubmit);
    
    let text = document.getElementById("text");
    text.addEventListener("keyup", updateResult);
    text.addEventListener("blur", updateResult);
    
    let amount = document.getElementById("amount");
    amount.addEventListener("change", updateResult);
    amount.addEventListener("blur", updateResult);
    <form id="form">
      <div>
        <label for="text">Text:</label>
        <textarea id="text"></textarea>
      </div>
      <div>
        <label for="amount">Amount:</label>
        <input id="amount" />
      </div>
    </form>
    <p>CaesarShift: <span id="output"></span></p>

    【讨论】:

    • 有什么解释吗?你到底做了什么或改变了什么?这段代码是如何工作的?
    • 谢谢!我不知道我怎么没看到。但是有没有办法让字符串和班次号码成为用户输入?
    • 是的,您需要添加input 字段,然后获取它们的值。您可以根据我上面的示例自行尝试,如果不能,您可以通过分享您尝试过的内容来打开另一个问题。
    • 这就是要问的问题。我不知道如何用 javascript 询问字符串和班次号码,而不是像提交表单这样的事情。
    • @PythonicOreo,我已经更新了我的答案以实现您正在寻找的内容。如果这有帮助,请考虑接受它:)——我还添加了一个基本检查来查看金额是否为数字。如果您还有其他问题,请告诉我。您可以单击“运行代码sn-p”来测试代码。另外,请查看developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/…——这应该可以帮助您了解正在发生的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多