返回后javascript onkeypress调用函数

时间:2013-06-28 23:07:18

标签: javascript

使用Javascript的onKeypress尝试在返回后调用函数。 这不起作用,因为由于验证数字,该字段尚未完成。

onKeyPress="return numbersonly(event, false);
            anotherfunction();"

使这个棘手的是返回必须在调用“anotherfunction()”之前发生。

3 个答案:

答案 0 :(得分:1)

使用此:

onkeypress="if (numbersonly(event, false)) {anotherfunction(); return true;} else {return false}"

由于像这样的长内联Javascript会让我感到困惑,我会将其移到一个函数中:

function maybe_another(event) {
    if (numbersonly(event, false)) {
      anotherfunction();
      return true;
    } else {
      return false
    }
 }

然后使用:

onkeypress="return maybe_another(event)"
输入元素中的

答案 1 :(得分:0)

这将在函数返回后调用anotherFunction():

onKeyPress="setTimeout(anotherFunction, 0); return numbersonly(event, false);">

它与Barmar的回答略有不同。他在调用numbersOnly之后调用anotherFunction,但在事件处理程序返回之前。我会在事件处理程序返回后调用anotherFunction。两者在不同的情况下都很有用。

请注意,如果要将参数传递给anotherFunction,则应执行以下操作:

onKeyPress="setTimeout(function(){anotherFunction(1,2,3);}, 0); return numbersonly(event, false);">

答案 2 :(得分:0)

尝试类似:

function E(e){
  return document.getElementById(e);
}
function FirstFunction(event, truthiness){
  return 'Truthiness was set to '+truthiness;
  //of course you must really be trying to run something from the Event
  //Object or you don't need the event argument in this function or the
  //keyup function below
}
function SecondFunction(e){
  E(e).innerHTML = this.value;
}
E('txt').onkeyup = function(ev){
  var e = ev || window.event;
  E('out1').innerHTML = FirstFunction(ev, false);
  SecondFunction.call(this, 'out2');
}

如果您还不理解callthis,那很好。关键是要向您展示您可以在分配给事件监听器的函数中放置任意数量的函数。此编程样式可以保存在外部JavaScript文件中,该文件将缓存在用户浏览器中。有些人将其称为Jnobtrusive JavaScript,因为它不在您的HTML中。另一方面,如果由于某种原因没有意义,坚持使用Obtrusive JavaScript,就是将SecondFunction传递给FirstFunction并在return值之前执行它,例如:

function FirstFunction(func, funcArg, anotherFunc, anotherFuncArg){
  func(funcArg);
  anotherFunc(anotherFuncArg);
}
function SecondFunction(e){
  E(e).innerHTML = 'this is just a test';
}
<input type='text' onkeyup='FirstFunction(SecondFunction, "out", function(){console.log = "You can use an Anonymous Function the same way"})' name='txt' id='txt' />

这将向您展示如何将未执行的函数作为参数传递。稍后再使用该参数。函数名在JavaScript中基本可变。在PHP中,您可以执行相同类型的操作,只需将函数转换为String。

大多数JavaScript程序员首选方法。请参阅下面的小提琴,以获取完整示例。

http://jsfiddle.net/PHPglue/3q4DC/4/

相关问题