事件未发生时在Javascript中执行函数

时间:2014-01-21 12:47:50

标签: javascript

我有以下内容:

<input type="text" name="field1" onblur="numericField(this);" />

但是我还需要在提交表单之前为元素执行numericField()。 我尝试document.getElementById("Campo1").onblur(),但它返回undefined。我怎么能这样做?

2 个答案:

答案 0 :(得分:-1)

如果您在提交之前需要做某事,我建议您编写验证功能。它更加透明。 示例:JQuery

<form id="form">
...
</form>

您可以在提交表单之前使用以下jQuery代码执行某些操作:

$(function() {
    $('#form').submit(function() {
        // DO STUFF
        return true; // return false to cancel form action
    });
});

答案 1 :(得分:-1)

首先,以你的方式绑定事件并不是一个好主意。相反,请改用element.addEventListener

根据您的问题猜测,您希望在提交表单之前进行验证。在这种情况下,你应该写:

document.querySelector("form").addEventListener("submit",function(){

  // validate your fields - basically run numericField() on both your input fields
  // if your numericField correctly returns true or false, the submit element will
  // be canceled if validation fails
  return numericField(your_element);
});

如果你真的不想在特定元素上发出模糊事件,可以执行以下操作:

var el = document.querySelector("<select your element here>");
el.focus();
el.blur();

同样使用HTML5,您现在可以直接验证模糊上的输入字段并正确定义类型(例如,如果它是数字,则将类型设置为数字)和/或pattern属性{{3} }。现在浏览器内在验证直接触发模糊。