日期:2014-05-16  浏览次数:20326 次

with (field) 这叫什么语句啊?

<html>
<head>
<script type="text/javascript">

function validate_required(field,alerttxt)
{
  with (field)
  {
     if (value==null||value=="")
     {
         alert(alerttxt);
         return false;
     }
     else 
     {
         return true;
     }
  }
}

function validate_email(field,alerttxt)
{
   with (field)
   {
      apos=value.indexOf("@")
      dotpos=value.lastIndexOf(".")
      if ( apos < 1 || dotpos-apos < 2 ) 
      {
         alert(alerttxt);
         return false;
      }
      else 
      {
         return true;
      }
   }
}

function validate_form(thisform)
{
  with ( thisform )
  {
     if (validate_required(email,"Email must be filled out!")==false)
     {
         email.focus();
         return false;
     }
     if (validate_email(email,"Not a valid e-mail address!")==false)
     {
         email.focus();
         return false;
     }
  }
}
</script>
</head>

<body>
<form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit"> 
</form>
</body>

</html>


上面代码里面的with (field),with ( thisform )这是什么语句啊?它的作用是什么?
------解决方案--------------------
with 语句用于设置代码在特定对象中的作用域。它的语法:with (expression) statement例如:var sMessage = "hello";with(sMessage) {alert(toUpperCase()); //输出 "HELLO"}在这个例子中,with 语句用于字符串,所以在调用 toUpperCase() 方法时,解释程序将检查该方法是否是本地函数。如果不是,它将检查伪对象 sMessage,看它是否为该对象的方法。然后,alert 输出 "HELLO",因为解释程序找到了字符串 "hello" 的 toUpperCase() 方法。提示:with 语句是运行缓慢的代码块,尤其是在已设置了属性值时。大多数情况下,如果可能,最好避免使用它
------解决方案--------------------
简单理解就是 with(field)后,大括号内,你可以直接用字段名访问field的成员,即若field有value成员,则value将访问到field.value
不推荐使用,除了效率低外,还有阅读困难,容易出错等缺点