How do I make a javascript function a html attribute?

点点圈 提交于 2020-04-18 05:47:54

问题


I have a javascript variable with parameters, but I don't know how to pass it into my html code. The javascript code is taken from 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;

};

I want to pass it on to my HTML obviously. I have done some research, and have come across ways such as:

<p id="output"></p>

and then

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

but I don't know how to add it all together. How do I call the variable? For the string, I have a text area input box, and maybe a clicker for the second argument, the amount, but I don't know how to put it all together in the HTML.


回答1:


You'll need to up the JavaScript inside a script tag and the p tag that you are getting by id in the body of an html document, like so:

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

See the snippet below with a working example:

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>


来源:https://stackoverflow.com/questions/61094110/how-do-i-make-a-javascript-function-a-html-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!