当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 三种不同位置代码的写法

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 JavaScript 三种不同位置代码的写法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 341 ::
收藏到网摘: n/a

客户端脚本JavaScript在写法上其实有很多种方法,它们的放置位置也非常之多。 下面列举在三种不同的地方写JavaScript代码,实现的效果都是点击按钮button弹出alert警告框
第一种是最常见的,代码如下
html代码
<input type="button" value="按钮1" id="btn1" onclick="pop()">
js代码
function pop()
{
alert("在JavaScript函数处调用");
}
第二种是最简单的实现方式,代码如下
<input type="button" value="按钮2" id="btn2" onclick="javascript:alert('直接写函数');">
第三种方式相对复杂,代码如下
html代码
<input type="button" value="按钮3" id="btn3">
js代码
var obj=document.getElementById("btn3");//以下语句一定要放在定义btn3的下面,否则编译器是不能识别btn3的。
if(window.addEventListener)// Mozilla, Netscape, Firefox等浏览器
{
obj.addEventListener("click",fun,false);//注意这里的false
}
else //IE浏览器
{
obj.attachEvent("onclick",fun);
}
function fun()
{
alert("通过在函数中触发事件");
}
总结:三种写法方式实现的效果是完全一样的,应该说三种方式都是常用的,而且各有优缺点。。。。