JavaScript在网页中出现的位置

来源:互联网 发布:学生党淘宝店铺白菜价 编辑:程序博客网 时间:2024/05/16 04:53

 这个是需要我们了解的

 javascript 操作网页上元素  文档元素  文件对象模型 Document Object Model,简称DOM

 alert 警告 就是在我们输入信息的时候 出错弹出的窗口 或者 提示什么的时候弹出的窗口

1.写在网页中

    a.直接写在事件名称后面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script language="javascript"></script></head><body><link rel="stylesheet" type="text/css" href="1.css"/><form>输入姓名<input type="text"><input type="button" value="问候" onclick="alert('你好!');"></form></body></html>


    b.做成函数写在head中

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script language="javascript">function sayHello(){alert("hello !" + document.forms[0].xm.value);} </script></head><body><link rel="stylesheet" type="text/css" href="1.css"/><form>输入姓名<input type="text" name="xm"><input type="button" value="问候" onclick="sayHello()"></form></body></html>


2.存在于单独的js文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript" src="1.js"></script></head><body><form>输入姓名<input type="text" name="xm"><input type="button" value="问候" onclick="sayHello()"></form></body></html>

// JavaScript Documentfunction sayHello(){alert("hello !!!" + document.forms[0].xm.value);} 

3.没有表单<form>找元素

通过name

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript" src="1.js"></script></head><body>输入姓名<input type="text" name="xm"><input type="button" value="问候" onclick="sayHello()"></body></html>

// JavaScript Documentfunction sayHello(){alert("你好 !!!" + document.getElementsByName("xm")[0].value);} 


通过id

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript" src="1.js"></script></head><body>输入姓名<input type="text" id="xm"><input type="button" value="问候" onclick="sayHello()"></body></html>

// JavaScript Documentfunction sayHello(){alert("你好 !!!" + document.getElementsByName("xm")[0].value);} 


0 0