键入时的javascript输入格式不起作用

时间:2018-10-26 18:20:17

标签: javascript

我需要帮助。我有一个输入框,输入时需要建立特定的格式。 我需要121.22’37” W 这是我的代码

function formatField(f) {
  f = f.replace(/[^0-9A-Za-z]/g, "")
  var n = f
  if (f.length >= 3) n = f.substr(0, 3) + "." + f.substr(3, 3)
  if (f.length >= 5) n += "’" + f.substr(5, 5)
  if (f.length >= 7) n += "”" + f.substr(7, 1)
  if (f.length >= 9) n += "W"
  return n
}
<input class="mrcinput" ${disabled( 'LATITUDE')} id="LATITUDE" maxlength="10" name="LATITUDE" onkeyup="this.value=formatField(this.value);" size="25" title="Latitude" type="text" />

2 个答案:

答案 0 :(得分:1)

您的逻辑混乱。 固定代码如下。但是,这并不是一个好方法,因为很难编辑,因此您需要分别处理backspace

function formatField(source) {
  var n = '';
  f = source.replace(/[^0-9A-Za-z]/g, "")
  if (source[0] === ' ') f = ' ' + f;
  var n = f;

  if (f.length >= 3) n = f.substr(0, 3) + "." + f.substr(3, 2)
  if (f.length >= 5) n += "’" + f.substr(5, 2)
  if (f.length >= 7) n += "”"
  if (f.length >= 8) n += " W"
  return n
}
<input class="mrcinput" ${disabled( 'LATITUDE')} id="LATITUDE" maxlength="11" name="LATITUDE" onkeyup="this.value=formatField(this.value);" size="25" title="Latitude" type="text" />

答案 1 :(得分:0)

在前端使用字符串时,请注意要在哪里使用它以及可能导致代码暂停的原因。

您是否需要javascript中的字符串?注意单引号(')和双引号("),并确保使用反斜杠(\)对其进行转义。

在HTML元素中是否需要它?您可能需要分别将其分别转换为(&#39;和(&quot;),以便这些特殊字符不会意外缩短您的标记。