Javascript字符限制并使用getElementById调用函数

时间:2013-05-23 10:01:24

标签: javascript html dom

我有一个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);
}

但它不起作用......请帮助。

5 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

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

供将来参考:

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

答案 2 :(得分:0)

document.getElementById("firma").onkeypress = function(){
     return restrictCharacters.call(this/*becauseof 'this.blur()' */, this,event,alphaOnly);
};

答案 3 :(得分:0)

您可以从this

获取e.target
document.getElementById("firma").onkeypress = function(e) {
     restrictCharacters(e.target,e,alphaOnly);
}

答案 4 :(得分:0)

  

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