JavaScript事件处理(重要)

JavaScript的时间处理是当网页中发生某件事情的时候,它会调用我们的一些函数,或者调用我们一些语句

1.得到焦点的事件:onFocus 在用户为了输入而选择select,text,textarea等时

   

 <form action="" method="post" name="test">
    <input type ="text" name= "name" value ="gaoweigang" onFocus = "JavaScript:alert(document.test.name.value);">
    </form>

 onFocus = "JavaScript:alert(document.test.name.value);" 意思是

     1)当这个输入框得到焦点的时候,我们执行一段javascript语句。

     2)JavaScript: 指的后面是javascript的语句,这个可以省略,有没有都行

2.失去焦点事件: onBlur 在select ,text,password,textarea 失去焦点时

3.onChange :在select ,text, textarea 的值被改变且失去焦点时

4.onclick:在一个对象被鼠标点中时(button checkbox radio lik set submit text textarea等)

<img src = "head.jpg" onclick="alert('welcome, javascript!');"></img>

注意:alert里面要使用单引号,不能使用双引号,写的时候一定要注意,否则调试特别麻烦

5.onLoad (这个一般使用在body中):第一次把这个文档加载到我们的窗口的时候,触发onload事件

<body onload="alert('welcome!');">

 6.onUnload(一般使用在body中):当这个html文档被别的文档给替换的时候,比如刷新的时候,重新加载文档

<body onload="alert('welcome!');" onunload = "alert('bye-bye');">

7.onMouseOver :当鼠标移动到一个对象上时

 <img src ="head.jpg" onmouseover="alert('哈哈');" onmouseout="alert('嘿嘿');" /> 

8.onMouseOut  :当鼠标从一个对象移开时

9.onSelect        :当form对象中的内容选中时,eg:input对象中内容被选中时,就会触发该事件

 <input type="text" name="name" onselect ="alert(document.name.name.value);">

10.onSubmit:出现在用户通过提交按钮提交一个表单时。当我们点提交按钮时,表单还没有提交之前,会触发此事件

 <form name ="name"action="" method="post"  onsubmit="alert(document.name.submit.value);">
      <input type="text" name="name" onselect ="alert(document.name.name.value);">
      <input type="submit" name="submit" value ="提交">
   </form> 

 当我们确定提交后,表单才会提交

   2)onsubmit="return false"  意思是说: 当我点击提交按钮时,触发onsubmit事件,执行onsubmit中的内容,因为是return false,那么程序就不再继续往下执行了,到此为止,也就是提交不了。

   3)我们 可以 通过 onsubmit的 return的这个值 来确定 该表单时继续提交,还是不提交;这个非常重要,我们可以通过它来进行表单的验证。

下面我们来写一个简单的表单验证(实现了在客户端的检验)

<html>
  <head>
  <script type="text/javascript">
   function check(){//验证用户名是否为空
    if(document.name.username.value==""){
    alert("用户名必须填写");
    return false;
      }
    return true;   
 }
  </script>
   </head>
  
  <body>
  <form name ="name" action="index.jsp" method="post"  onsubmit="return check()">//根据check()的返回值来确定是不是要继续提交
      用户名:<input type="text" name="username"/>
      <input type="submit" name="submit" value ="提交">
   </form> 
  </body>
</html>
原文地址:https://www.cnblogs.com/SpringSmallGrass/p/3017369.html