当我更改输入时,如何在 HTML 表单上自动显示 JavaScript 函数的结果?

How can I automatically show the result of a JavaScript function on a HTML form, when I change the input?

我有一个带参数的 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。我做了一些研究,遇到了一些方法,例如:

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

然后

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

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

在我之前的问题中,, and my answer was an HTTP form. But I'm trying to create a site that has a lot of ways to decrypt 1 string. So if the user has to click submit every time, especially 25 times in this case, that's not going to be that helpful. Is there any way to make it live without a submit button? This is what I'm kind of going for, https://cryptii.com/pipes/caesar-cipher

您需要阻止点击按钮后的默认事件。

e.preventDefault(); // Do not submit!

此外,我完善了密码中的逻辑以解释负偏移。

注意: 没有理由调用 shift,如果它的数量为零,只是 return 收到的消息......除非你真的想让它清理非字母字符的消息。


更新:添加了一个没有按钮的动态表单。

注意我在下面创建的 addEventListeners 便利函数。它允许您为许多不同类型的事件向多个元素添加一个事件。它充其量是最基本的,但可以节省您添加每个事件侦听器的时间。更好的方法是对象。我可能会在底部添加一个替代示例。

const caesarShift = (str, amount) => {
  const LOWER_A = 'a'.charCodeAt(0) , LOWER_Z = 'z'.charCodeAt(0),
        UPPER_A = 'A'.charCodeAt(0) , UPPER_Z = 'Z'.charCodeAt(0),
        SIZE    = LOWER_Z - LOWER_A ;
  if (amount === 0) return str;
  let output = '';
  for (let i = 0; i < str.length; i++) {
    let c = str[i];
    if (c.match(/[a-z]/i)) {
      let offset = -1, code = str.charCodeAt(i);
      if (code >= LOWER_A && code <= LOWER_Z) {
        offset = LOWER_A;
      } else if (code >= UPPER_A && code <= UPPER_Z) {
        offset = UPPER_A;
      }
      if (offset !== -1) {
        c = String.fromCharCode(offset + ((code - offset) + amount + SIZE) % SIZE);
      }
    }
    output += c;
  }
  return output;
};

const form = document.forms['caesar-1'];
form.querySelector('button').addEventListener('click', (e) => {
  form.result.value = caesarShift(
    form.message.value,
    parseInt(form.amount.value, 10)
  );
  e.preventDefault(); // Do not submit!
});

const form2 = document.forms['caesar-2'];
addEventListeners('input, textarea', 'change keyup', (e) => {
  form2.result.value = caesarShift(
    form2.message.value,
    parseInt(form2.amount.value, 10)
  );
}, form2);

// Initial change events
triggerEvent(form.querySelector('button'), 'click');
triggerEvent(form2.message, 'change'); 

// Custom functions to make life easier...
function addEventListeners(selector, eventNames, eventFn, scope) {
  scope = scope || document;
  const names = eventNames.split(/\s+/g);
  selector.split(/\s*,\s*/).forEach(sel => {
    Array.from(scope.querySelectorAll(sel)).forEach(el => {
      names.forEach(eventName => el.addEventListener(eventName, eventFn));
    });
  });
}
function triggerEvent(el, eventName) {
  let event = document.createEvent('HTMLEvents');
  event.initEvent(eventName, true, false);
  el.dispatchEvent(event);
}
hr { margin: 1em 0; }

.form-field {
  margin-bottom: 0.5em;
}

.form-field label {
  display: inline-block;
  width: 4em;
  font-weight: bold;
}

form button {
  margin-left: 5em;
  margin-bottom: 0.5em;
}

.form-field-stacked {
  display: inline-block;
  vertical-align: top;
  margin-right: 0.5em;
}

.form-field-stacked label {
  display: block;
  margin-bottom: 0.25em;
  width: auto;
}

.form-field-stacked input[type="number"] {
  width: 3em;
}
<h2>Button Form</h2>
<form name="caesar-1">
  <div class="form-field">
    <label>Message</label>
    <input name="message" type="text" value="Hello World"/>
  </div>
  <div class="form-field">
    <label>Amount</label>
    <input name="amount" type="number" value="13" />
  </div>
  <button>Rotate</button>
  <div class="form-field">
    <label>Output</label>
    <input name="result" type="text" disabled="disabled" />
  </div>
</form>
<hr />
<h2>Dynamic Form</h2>
<form name="caesar-2">
  <div class="form-field form-field-stacked">
    <label>Message</label>
    <textarea name="message" rows="4" cols="24">Hello World</textarea>
  </div>
  <div class="form-field form-field-stacked">
    <label>Amount</label>
    <input name="amount" type="number" value="13" />
  </div>
  <div class="form-field form-field-stacked">
    <label>Output</label>
    <textarea name="result" rows="4" cols="24" disabled="disabled"></textarea>
  </div>
</form>


一个更动态的事件监听函数。

const caesarShift=(t,e)=>{if(r="a".charCodeAt(0),a="z".charCodeAt(0),o="A".charCodeAt(0),c="Z".charCodeAt(0),h=a-r,0===e)return t;let C="";for(let d=0;d<t.length;d++){let A=t[d];if(A.match(/[a-z]/i)){let C=-1,f=t.charCodeAt(d);f>=r&&f<=a?C=r:f>=o&&f<=c&&(C=o),-1!==C&&(A=String.fromCharCode(C+(f-C+e+h)%h))}C+=A}return C};

const form = document.forms['caesar'];
const handleUpdate = (e) => {
  form.result.value = caesarShift(
    form.message.value,
    parseInt(form.amount.value, 10)
  );
}

addEventListeners({
  selector : 'input',
  listeners : {
    'change' : handleUpdate,
    'keyup' : handleUpdate
  },
  scope: form
}, {
  selector : 'textarea',
  listeners : {
    'change' : handleUpdate,
    'keyup' : handleUpdate
  },
  scope: form
});

// Initial change events
triggerEvent(form.message, 'change'); 

// Custom functions to make life easier...
function addEventListeners(...configs) {
  configs.forEach(config => {
    let options = config.options || {};
    let els = Array.from((config.scope || document).querySelectorAll(config.selector));
    Object.keys(config.listeners || {}).forEach(eventName => {
      els.forEach(el => {
        el.addEventListener(eventName, config.listeners[eventName], options)
      });
    });
  });
}
function triggerEvent(el, eventName) {
  let event = document.createEvent('HTMLEvents');
  event.initEvent(eventName, true, false);
  el.dispatchEvent(event);
}
.form-field {
  margin-bottom: 0.5em;
}

.form-field label {
  font-weight: bold;
}

.form-field-stacked {
  display: inline-block;
  vertical-align: top;
  margin-right: 0.5em;
}

.form-field-stacked label {
  display: block;
  margin-bottom: 0.25em;
  width: auto;
}

.form-field-stacked input[type="number"] {
  width: 3em;
}
<h2>Dynamic Form</h2>
<form name="caesar">
  <div class="form-field form-field-stacked">
    <label>Message</label>
    <textarea name="message" rows="4" cols="24">Hello World</textarea>
  </div>
  <div class="form-field form-field-stacked">
    <label>Amount</label>
    <input name="amount" type="number" value="13" />
  </div>
  <div class="form-field form-field-stacked">
    <label>Output</label>
    <textarea name="result" rows="4" cols="24" disabled="disabled"></textarea>
  </div>
</form>