HTML 表单:id 和名称更改时 onblur 事件不起作用

HTML form: onblur event does not work when id and name changed

我有这个 HTML 形式,当这样写时工作正常:

<fieldset>
  <label for="name">Name</label>
  <input type="text" name="name" id="name" onblur="validateName(name)" />
  <span id="nameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
</fieldset>

但是当我将第 3 行和第 4 行更改为:

<input type="text" name="firstname" id="firstname" onblur="validateName(firstname)" />

<span id="firstnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>

,onblur 不起作用!怎么会这样?毕竟我只是改了名字和ID?

这是我的 validateName(name) 函数:

function validateName(x) {
  // Validation rule
  var re = /[A-Za-z -']$/;
  // Check input
  if (re.test(document.getElementById(x).value)) {
    // Style green
    document.getElementById(x).style.background = '#ccffcc';
    // Hide error prompt
    document.getElementById(x + 'Error').style.display = "none";
    return true;
  } else {
    // Style red
    document.getElementById(x).style.background = '#e35152';
    // Show error prompt
    document.getElementById(x + 'Error').style.display = "block";
    return false;
  }
}

谢谢

您也需要更改错误元素的 ID(因为 x + Error)。

<span id="firstnameError"...>

并将函数参数放入引号中:

<input type="text" name="firstname" id="firstname" onblur="validateName('firstname')" />

http://jsfiddle.net/Lgp55uwo/