如何在Javascript中将事件对象传递给函数? [英] How to pass an event object to a function in Javascript?

查看:77
本文介绍了如何在Javascript中将事件对象传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function check_me() {
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     return false; 
   } else { 
    return true; }
}

在Firefox中,当我尝试提交一个空值时,它会抛出错误并将焦点设置回元素。但同样的事情在IE中不会发生,因为它会引发错误并在单击确定后发布表单(返回true)。

In Firefox, when I try to submit an empty value it throws up the error and sets the focus back to element. But same thing doesn't happen in IE as it throws up error and after clicking OK and posts the form (returns true).

如何避免这种情况?我正在考虑使用event.preventDefault()避免这种情况,但我不知道如何使用此方法执行此操作。我尝试通过checkme(事件)..但它没有工作。我正在使用Prototype js。

How I can avoid this? I was thinking to avoid this using event.preventDefault(), but I am not sure how to do this using this method. I tried passing checkme(event) .. but it didnt work. I am using Prototype js.

(我知道如何在javascript中绑定.click函数时传递事件..而不是在html中调用onclick ..使用Jquery ,但我必须调试这段代码)

(I know how to pass an event when I bind an .click function in javascript.. instead of calling onclick within html .. using Jquery, but I have to debug this piece of code)

推荐答案

尝试使onclick js使用'return'来确保所需的返回值被使用...

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

这篇关于如何在Javascript中将事件对象传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆