Javascript----常用小技巧

一.js的各种消息框

(以下代码来自w3school)

  1.警告框

  
    
alert( " 消息内容 " )

  2.确认框

代码
   
     
< html >
< head >
< script type = " text/javascript " >
function disp_confirm()
{
var r = confirm( " 按下按钮 " )
if (r == true )
{
document.write(
" 您按了确认! " )
}
else
{
document.write(
" 您按了取消! " )
}
}
< / script>
< / head>
< body >

< input type = " button " onclick = " disp_confirm() " value = " 显示确认框 " / >

< / body>
< / html>

 

 

  3.提示框  

 

代码
   
     
< html >
< head >
< script type = " text/javascript " >
function disp_prompt()
{
var name = prompt( " 请输入您的名字 " , " Bill Gates " )
if (name != null && name != "" )
{
document.write(
" 你好! " + name + " 今天过得怎么样? " )
}
}
< / script>
< / head>
< body >

< input type = " button " onclick = " disp_prompt() " value = " 显示提示框 " / >

< / body>
< / html>

二.事件

  FF: Firefox, N: Netscape, IE: Internet Explorer

属性 当以下情况发生时,出现此事件 FF N IE
onabort 图像加载被中断 1 3 4
onblur 元素失去焦点 1 2 3
onchange 用户改变域的内容 1 2 3
onclick 鼠标点击某个对象 1 2 3
ondblclick 鼠标双击某个对象 1 4 4
onerror 当加载文档或图像时发生某个错误 1 3 4
onfocus 元素获得焦点 1 2 3
onkeydown 某个键盘的键被按下 1 4 3
onkeypress 某个键盘的键被按下或按住 1 4 3
onkeyup 某个键盘的键被松开 1 4 3
onload 某个页面或图像被完成加载 1 2 3
onmousedown 某个鼠标按键被按下 1 4 4
onmousemove 鼠标被移动 1 6 3
onmouseout 鼠标从某元素移开 1 4 4
onmouseover 鼠标被移到某元素之上 1 2 3
onmouseup 某个鼠标按键被松开 1 4 4
onreset 重置按钮被点击 1 3 4
onresize 窗口或框架被调整尺寸 1 4 4
onselect 文本被选定 1 2 3
onsubmit 提交按钮被点击 1 2 3
onunload 用户退出页面 1 2 3

三.try...catch异常处理

 

代码
   
     
< html >
< head >
< script type = " text/javascript " >
var txt = ""
function message()
{
try
{
adddlert(
" Welcome guest! " )
}
catch (err)
{
txt
= " 本页中存在错误。\n\n "
txt
+= " 点击“确定”继续查看本页,\n "
txt
+= " 点击“取消”返回首页。\n\n "
if ( ! confirm(txt))
{
document.location.href
= " /index.html "
}
}
}
< / script>
< / head>

< body >
< input type = " button " value = " 查看消息 " onclick = " message() " / >
< / body>

< / html>

 

throw的异常抛出,可以是字符串、整数、逻辑值或者对象

 

代码
   
     
< html >
< body >
< script type = " text/javascript " >
var x = prompt( " 请输入 0 至 10 之间的数: " , "" )
try
{
if (x > 10 )
throw " Err1 "
else if (x < 0 )
throw " Err2 "
else if (isNaN(x))
throw " Err3 "
}
catch (er)
{
if (er == " Err1 " )
alert(
" 错误!该值太大! " )
if (er == " Err2 " )
alert(
" 错误!该值太小! " )
if (er == " Err3 " )
alert(
" 错误!该值不是数字! " )
}
< / script>
< / body>
< / html>

四.异常捕捉onerror

 

代码
   
     
< html >
< head >
< script type = " text/javascript " >
onerror
= handleErr
var txt = ""

function handleErr(msg,url,l)
{
txt
= " 本页中存在错误。\n\n "
txt
+= " 错误: " + msg + " \n "
txt
+= " URL: " + url + " \n "
txt
+= " 行: " + l + " \n\n "
txt
+= " 点击“确定”继续。\n\n "
alert(txt)
return true
}

function message()
{
adddlert(
" Welcome guest! " )
}
< / script>
< / head>

< body >
< input type = " button " value = " 查看消息 " onclick = " message() " / >
< / body>

< / html>

你可能感兴趣的:(JavaScript)