2

我有一个 JS 函数,可以检查和限制输入表单中输入的某些字符。代码如下所示:

var alphaOnly = /[sA-Za-z\söÖäÄüÜ]/g;
var alphaextraOnly = /[A-Za-z\-&/'"\öÖäÄüÜ]/g;
var alphadigitsOnly = /[sA-Za-z\söÖäÄüÜ\s1234567890]/g;
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var mailOnly = /[a-z\.@]/g;

function restrictCharacters(myfield, e, restrictionType) {
  if (!e) var e = window.event
  if (e.keyCode) code = e.keyCode;
  else if (e.which) code = e.which;
  var character = String.fromCharCode(code);
  // if they pressed esc... remove focus from field...
  if (code==27) { this.blur(); return false; }
  // ignore if they are press other keys
  // strange because code: 39 is the down key AND ' key...
  // and DEL also equals .
  if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
    if (character.match(restrictionType)) {
      return true;
    } else {
      return false;
    }
  }   
}

当我onkeypress像这样添加到输入时它会起作用:

<input type="text" class="span4 register_input" id="firma" name="firma" onkeypress="return restrictCharacters(this, event, alphaOnly);" />

但我想getElementById在脚本中做到这一点。我试图添加这个:

window.onload = function() {
  document.getElementById("firma").onkeypress = restrictCharacters(this, event, alphaOnly);
}

但它没有用......请帮助。

4

5 回答 5

2

您不能将这样的参数传递给 onkeypress 您需要使用包装函数

document.getElementById("firma").onkeypress = function (e)
    {
        return restrictCharacters(this,e,alphaOnly);
    };

jsFiddle http://jsfiddle.net/BjU2e/5/

于 2013-05-23T10:06:12.963 回答
1

您将结果分配给 onkeypressrestrictCharacters(this,event,alphaOnly)而不是函数委托。正确的版本在以下 jsFiddle 中:http: //jsfiddle.net/xL47r/1/

供将来参考:

document.getElementById("firma2").onkeypress = function(e) {
    return restrictCharacters(this,e,alphaOnly); 
};
于 2013-05-23T10:05:54.277 回答
0
document.getElementById("firma").onkeypress = function(){
     return restrictCharacters.call(this/*becauseof 'this.blur()' */, this,event,alphaOnly);
};
于 2013-05-23T10:07:41.980 回答
0

你可以thise.target

document.getElementById("firma").onkeypress = function(e) {
     restrictCharacters(e.target,e,alphaOnly);
}
于 2013-05-23T10:08:38.820 回答
0

您将事件与 dom 绑定的语法错误。这里是:window.onload = function () { var ab = document.getElementById("firma"); ab.setAttribute("onkeypress", "restrictCharacters(this,event, true)"); }

于 2013-05-23T10:17:59.747 回答