JavaScript DOM编程艺术——综合案例

文章目录

      • HTML代码
        • template.html
        • index.html
        • about.html
        • photos.html
        • live.html
        • contact.html
      • CSS代码
        • layout.css
        • color.css
        • typography.css
        • basic.css
      • JS代码

HTML代码

template.html
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jay Skript and Domsterstitle>
    <link rel="stylesheet" media="screen" href="styles/basic.css">
head>
<body>
<header>
    <img src="images/logo.gif" alt="Jay Skript and the Domsters">
    <nav>
        <ul>
            <li><a href="index.html">Homea>li>
            <li><a href="about.html">Abouta>li>
            <li><a href="photos.html">Photosa>li>
            <li><a href="live.html">Livea>li>
            <li><a href="contact.html">Contacta>li>
        ul>
    nav>
header>
<article>
    <h1>Lorem Ipsum Dolorh1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras varius accumsan tellus, in pulvinar lacus fermentum ut. Phasellus sem ante, rhoncus congue pellentesque a, pellentesque in purus. Aliquam in rutrum nulla. Nunc ut turpis a enim aliquam dapibus vitae scelerisque arcu. Ut condimentum nisi aliquet, molestie velit sed, aliquam arcu. Curabitur at est vel quam fringilla tincidunt. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque lobortis sed quam nec hendrerit. Proin dolor massa, pulvinar ut vestibulum ut, euismod vulputate diam. Quisque nec accumsan lacus, eu ullamcorper orci. Praesent condimentum feugiat vulputate. Suspendisse pulvinar, erat non finibus bibendum, erat urna dictum velit, nec pharetra magna mauris vel massa. Quisque sodales orci vitae ipsum rutrum, et ullamcorper leo posuere. Mauris dapibus ligula quam, nec pharetra ex porta nec. Mauris feugiat, nibh non varius tempus, massa turpis convallis risus, id tempor neque ante vel felis.p>
article>
<script src="scripts/global.js">script>
body>
html>

index.html
DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Jay Skript and the Domsterstitle>
	
	<script type="text/javascript" src="scripts/global.js">script>
	<link rel="stylesheet" media="screen" href="styles/basic.css" />
head>
<body>
	<header>
		<img src="images/logo.gif" alt="Jay Skript and the Domsters" />
		<nav>
			<ul>
				<li><a href="index.html">Homea>li>
				<li><a href="about.html">Abouta>li>
				<li><a href="photos.html">Photosa>li>
				<li><a href="live.html">Livea>li>
				<li><a href="contact.html">Contacta>li>
			ul>
		nav>
	header>
	<article>
		<p id="intro">
		Welcome to the official website of Jay Skript and the Domsters.
		Here, you can <a href="about.html" title="About">learn more about the banda>,
		view <a href="photos.html" title="Photos">photos of the banda>,
		find out about <a href="live.html" title="Tour Date">tour datesa>
		and <a href="contact.html" title="Contact">get in touch with the banda>.
		p>
	article>
body>
html>
about.html
DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Jay Skript and the Domsterstitle>
	<script type="text/javascript" src="scripts/global.js">script>
	<link rel="stylesheet" media="screen" href="styles/basic.css" />
head>
<body>
	<header>
		<img src="images/logo.gif" alt="Jay Skript and the Domsters" />
		<nav>
			<ul>
				<li><a href="index.html">Homea>li>
				<li><a href="about.html">Abouta>li>
				<li><a href="photos.html">Photosa>li>
				<li><a href="live.html">Livea>li>
				<li><a href="contact.html">Contacta>li>
			ul>
		nav>
	header>
	<article>
		<h1>About the bandh1>
		<nav>
			<ul>
				<li><a href="#jay">Jay Skripta>li>		
					
				<li><a href="#domsters">The Domstersa>li>
			ul>
		nav>
		<section id="jay">
			<h2>Jay Skripth2>
			<p>Jay Skript is going to rock your world!p>
			<p>Together with his compatriots The Domsters, Jay is set for world domination. Just you wait and see.p>
			<p>Jay Skript has been on the scene since the mid nineties. His talent hasn't always been recognized or fully appreciated. In the early days, he was often unfavorably compared to bigger, similarly-named artists. That's all in the past now.p>
		section>
		<section id="domsters">
			<h2>The Domstersh2>
			<p>The Domsters have been around, in one form or another, for almost as long. It's only in the past few years that The Domsters have settled down to their current, stable line-up. Now they're a rock-solid bunch: methodical and dependable.p>
		section>
	article>
body>
html>
photos.html
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Jay Skript And The Domsters: Photostitle>
  <link rel="stylesheet" type="text/css" media="screen" href="styles/basic.css" />
  <script type="text/javascript" src="scripts/global.js">script>
head>
<body>
	<header>
		<img src="images/logo.gif" alt="Jay Skript and the Domsters" />
		<nav>
			<ul>
				<li><a href="index.html">Homea>li>
				<li><a href="about.html">Abouta>li>
				<li><a href="photos.html">Photosa>li>
				<li><a href="live.html">Livea>li>
				<li><a href="contact.html">Contacta>li>
			ul>
		nav>
	header>
  <article id="content">
    <h1>Photos of the bandh1>
    <ul id="imagegallery">
      <li>
        <a href="images/concert.jpg" title="The crowd goes wild">
          <img src="images/photos/thumbnail_concert.jpg" alt="the band in concert" />
        a>
      li>
      <li>
        <a href="images/bassist.jpg" title="An atmospheric moment">
          <img src="images/photos/thumbnail_bassist.jpg" alt="the bassist" />
        a>
      li>
      <li>
        <a href="images/guitarist.jpg" title="Rocking out">
          <img src="images/photos/thumbnail_guitarist.jpg" alt="the guitarist" />
        a>
      li>
      <li>
        <a href="images/crowd.jpg" title="Encore! Encore!">
          <img src="images/photos/thumbnail_crowd.jpg" alt="the audience" />
        a>
      li>
    ul>
  article>
body>
html>
live.html
DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Jay Skript and the Domsterstitle>
	
	<script type="text/javascript" src="scripts/global.js">script>
	<link rel="stylesheet" media="screen" href="styles/basic.css" />
head>
<body>
	<header>
		<img src="images/logo.gif" alt="Jay Skript and the Domsters" />
		<nav>
			<ul>
				<li><a href="index.html">Homea>li>
				<li><a href="about.html">Abouta>li>
				<li><a href="photos.html">Photosa>li>
				<li><a href="live.html">Livea>li>
				<li><a href="contact.html">Contacta>li>
			ul>
		nav>
	header>
	<article id="content">
		<h1>Tour datesh1>
		<table summary="when and where you can see the band">
		  <thead>
		  <tr>
			<th>Dateth>
			<th>Cityth>
			<th>Venueth>
		  tr>
		  thead>
		  <tbody>
		  <tr>
			<td>June 9thtd>
			<td>Portland, <abbr title="Oregon">ORabbr>td>
			<td>Crystal Ballroomtd>
		  tr>
		  <tr>
			<td>June 10thtd>
			<td>Seattle, <abbr title="Washington">WAabbr>td>
			<td>Crocodile Cafetd>
		  tr>
		  <tr>
			<td>June 12thtd>
			<td>Sacramento, <abbr title="California">CAabbr>td>
			<td>Torch Clubtd>
		  tr>
		  <tr>
			<td>June 17thtd>
			<td>Austin, <abbr title="Texas">TXabbr>td>
			<td>Speakeasytd>
		  tr>
		  tbody>
		table>
	article>
body>
html>
contact.html
DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Jay Skript and the Domsterstitle>
	<script type="text/javascript" src="scripts/modernizr-1.6.min.js">script>
	<script type="text/javascript" src="scripts/global.js">script>
	<link rel="stylesheet" media="screen" href="styles/basic.css" />
head>
<body>
	<header>
		<img src="images/logo.gif" alt="Jay Skript and the Domsters" />
		<nav>
			<ul>
				<li><a href="index.html">Homea>li>
				<li><a href="about.html">Abouta>li>
				<li><a href="photos.html">Photosa>li>
				<li><a href="live.html">Livea>li>
				<li><a href="contact.html">Contacta>li>
			ul>
		nav>
	header>
	<article id="content">
		<h1>Contact the bandh1>
		<form method="post" action="submit.html">
		  <fieldset>
			<p>
			 <label for="name">Name:label>
			 <input type="text" id="name" name="name" placeholder="Your name" required="required" />
			p>
			<p>
			 <label for="email">Email:label>
			 <input type="text" id="email" name="email" placeholder="Your email address" required="required" />
			p>
			<p>
			 <label for="message">Message:label>
			 <textarea cols="45" rows="7" id="message" name="message" placeholder="Write your message here." required="required">textarea>
			p>
			<input type="submit" value="Send" />
		   fieldset>
		form>
	article>
body>
html>

CSS代码

layout.css
*{
    padding: 0;
    margin: 0;
}
section,header,article,nav{
    display: block;
}
body{
    margin: 1em 10%;
    background-image: url(../images/background.gif);
    background-attachment:fixed;    
    background-position: top left;
    background-repeat: repeat-x;
    max-width: 80em;
}
header{
    background-image: url(../images/guitarist.gif);
    background-repeat: no-repeat;
    background-position: bottom right;
    border-width: 0.1em;
    border-style: solid;
    border-bottom-width: 0;
}
header nav{
    background-image: url(../images/navbar.gif);
    background-position: bottom left;
    background-repeat: repeat-x;
    border-width: 0.1em;
    border-style: solid;
    border-top-width: 0;
    border-bottom-width: 0;
    padding-left: 10%;
}
header nav ul{
    width: 100%;
    overflow: hidden;
    border-left: 0.1em solid;
}
header nav li{
    display: inline;
}
header nav li a{
    float: left;
    padding: 0.5em 2em;
    border-right: 0.1em solid;
}
article{
    border: 0.1em solid;
    border-top-width: 0;
    padding:2em 10%;
    line-height: 1.8em;
}
article img{
    border-width: 0.1em;
    border-style: solid;
    outline-width: 0.1em;
    outline-style: solid;
}
#about header{
    background-image: url(../images/lineup.gif);
}
#photos header{
    background-image: url(../images/basshead.gif);
}
#live header{
    background-image: url(../images/bassist.gif);
}
#contact header{
    background-image: url(../images/drummer.gif);
}
#slideshow{
    width: 150px;
    height: 150px;
    position: relative;
    overflow: hidden;
}
#preview{
    position: absolute;
    border-width: 0;
    outline-width: 0;
}
#frame{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
}
#imagegallery li{
    display: inline;
}
td{
    padding: 0.5em 3em;
}
th{
    color: #edc;
    background-color: #455;
}
tr td{
    color: #233;
    background-color: #eb6;
}
dl{
    overflow: hidden;
}
dt{
    float: left;
}
dd{
    float: left;
}
label{
    display: block;
}
fieldset{
    border:0;
}
color.css
body {
    color: #fb5;
    background-color: #334;
}
a:link {
    color: #445;
    background-color: #eb6;
}
a:visited {
    color: #345;
    background-color: #eb6;
}
a:hover {
    color: #667;
    background-color: #fb5;
}
a:active {
    color: #778;
    background-color: #ec8;
}
header {
    color: #ec8;
    background-color: #334;
    border-color: #667;
}
header nav {
    color: #455;
    background-color: #789;
    border-color: #667;
}
article {
    color: #223;
    background-color: #edc;
    border-color: #667;
}
header nav ul {
    border-color: #99a;
}
header nav a:link,header nav a:visited {
    color: #eef;
    background-color: transparent;
    border-color: #99a;
}
header nav a:hover {
    color: #445555;
    background-color: #ec8;
}
header nav a:active {
    color: #667;
    background-color: #ec8;
}
article img {
    border-color: #ba9;
    outline-color: #dcb;
}
#imagegallery a {
    background-color: transparent;
}
header nav a.here:link,header nav a.here:visited,header nav a.here:hover,header nav a.here:active{
    color: #eef;
    background-color: #799;
}
tr.odd td{
    color: #233;
    background-color: #ec8;
}
tr.highlight td{
    color:#233;
    background-color: #cba;
}
input.placeholder {
    color:grey;
}
typography.css
body {
	font-size: 76%;
	font-family: "Helvetica","Arial",sans-serif;
}
body * {
	font-size: 1em;
}
a {
	font-weight: bold;
	text-decoration: none;
}
header nav {
	font-family: "Lucida Grande","Helvetica","Arial",sans-serif;
}
header nav a {
	text-decoration: none;
	font-weight: bold;
}
article {
	line-height: 1.8em;
}
article p {
	margin: 1em 0;
}
h1 {
	font-family: "Georgia","Times New Roman",sans-serif;
	font: 2.4em normal;
}
h2 {
	font-family: "Georgia","Times New Roman",sans-serif;
	font: 1.8em normal;
	margin-top: 1em;
}
h3 {
	font-family: "Georgia","Times New Roman",sans-serif;
	font: 1.4em normal;
	margin-top: 1em;
}
#imagegallery li {
	list-style-type: none;
}
textarea {
	font-family: "Helvetica","Arial",sans-serif;
}
dt{
	margin-right: 1em;
}
dd{
	margin-right: 3em;
}
basic.css
@import "layout.css";
@import "color.css";
@import "typography.css";

JS代码

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}
function insertAfter(newElement, targetElement) {
    var parent = targetElement.parentNode;
    if (parent.lastChild == targetElement) {
        parent.appendChild(newElement);
    } else {
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}
function addClass(element, value) {
    if (!element.className) {
        element.className = value;
    } else {
        newClassName = element.className;
        newClassName += " ";
        newClassName += value;
        element.className = newClassName;
    }
}
function highlightPage() {
    if (!document.getElementById) return false;
    if (!document.getElementsByTagName) return false;
    var headers = document.getElementsByTagName("header");
    if (headers.length == 0) return false;
    var navs = headers[0].getElementsByTagName("nav");
    if (navs.length == 0) return false;
    var links = navs[0].getElementsByTagName("a");
    var linkurl;
    for (var i = 0; i < links.length; i++) {
        linkurl = links[i].getAttribute("href");
        if (window.location.href.indexOf(linkurl) != -1) {
            links[i].className = "here";
            var linktext = links[i].lastChild.nodeValue.toLowerCase();
            document.body.setAttribute("id", linktext);
        }
    }
}
addLoadEvent(highlightPage);
function moveElement(elementID, final_x, final_y, interval) {
    if (!document.getElementById) return false;
    var elem = document.getElementById(elementID);
    //当movement属性存在时,清除积累在setTimeout中的事件
    if (elem.movement) {
        clearTimeout(elem.movement);
    }
    if (!elem.style.left) {
        elem.style.left = "0px";
    }
    if (!elem.style.top) {
        elem.style.top = "0px";
    }
    var xpos = parseInt(elem.style.left);
    var ypos = parseInt(elem.style.top);
    var dist = 0;
    if (xpos == final_x && ypos == final_y) return true;
    if (xpos < final_x) {
        dist = Math.ceil((final_x - xpos) / 10)
        xpos += dist;
    }
    if (xpos > final_x) {
        dist = Math.ceil((xpos - final_x) / 10);
        xpos -= dist;
    }
    if (ypos < final_y) {
        dist = Math.ceil((final_y - ypos) / 10);
        ypos += dist;
    }
    if (ypos > final_y) {
        dist = Math.ceil((ypos - final_y) / 10);
        ypos -= dist;
    }
    elem.style.left = xpos + "px";
    elem.style.top = ypos + "px";
    //moveElement(elementID,final_x,final_y,interval)
    var repeat = "moveElement('" + elementID + "'," + final_x + "," + final_y + "," + interval + ")";
    // movement = setTimeout(repeat,interval);     不使用var 隐式的定义了全局变量
    //此处使用全局变量不合适,当用户移动链接较快时,movement变量一直在变化,导致动画滞后
    //全局、局部变量都不可使用,可为elem添加属性
    elem.movement = setTimeout(repeat, interval);
}
function prepareSlideshow() {
    if (!document.getElementById) return false;
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById("intro")) return false;
    var slideshow = document.createElement("div");
    slideshow.setAttribute("id", "slideshow");
    var frame = document.createElement("img");
    frame.setAttribute("src", "images/frame.gif");
    frame.setAttribute("alt", "");
    frame.setAttribute("id", "frame");
    slideshow.appendChild(frame);
    var preview = document.createElement("img");
    preview.setAttribute("src", "images/slideshow.gif");
    preview.setAttribute("alt", "a glimpse of what awaits you");
    preview.setAttribute("id", "preview");
    slideshow.appendChild(preview);
    var intro = document.getElementById("intro");
    insertAfter(slideshow, intro);
    var links = document.getElementsByTagName("a");
    var destination;
    for (var i = 0; i < links.length; i++) {
        links[i].onmouseover = function () {
            destination = this.getAttribute("href");
            if (destination.indexOf("index.html") != -1) {
                moveElement("preview", 0, 0, 5);
            }
            if (destination.indexOf("about.html") != -1) {
                moveElement("preview", -150, 0, 5);
            }
            if (destination.indexOf("photos.html") != -1) {
                moveElement("preview", -300, 0, 5);
            }
            if (destination.indexOf("live.html") != -1) {
                moveElement("preview", -450, 0, 5);
            }
            if (destination.indexOf("contact.html") != -1) {
                moveElement("preview", -600, 0, 5);
            }
        }
    }
}
addLoadEvent(prepareSlideshow);
function showSection(id) {
    var sections = document.getElementsByTagName("section");
    for (var i = 0; i < sections.length; i++) {
        if (sections[i].getAttribute("id") == id) {
            sections[i].style.display = "block";
        } else {
            sections[i].style.display = "none";
        }
    }
}
function prepareInternalnav() {
    var articles = document.getElementsByTagName("article");
    if (articles.length == 0) return false;
    var navs = articles[0].getElementsByTagName("nav");
    if (navs.length == 0) return false;
    var nav = navs[0];
    var links = nav.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        var sectionId = links[i].getAttribute("href").split("#")[1];
        if (!document.getElementById(sectionId)) continue;
        document.getElementById(sectionId).style.display = "none";
        links[i].destination = sectionId;
        links[i].onclick = function () {
            showSection(this.destination);
            return false;
        }
    }
}
addLoadEvent(prepareInternalnav);
function preparePlaceholder() {
    if (!document.createElement) return false;
    if (!document.createTextNode) return false;
    if (!document.getElementById) return false;
    if (!document.getElementById("imagegallery")) return false;
    var placeholder = document.createElement("img");
    placeholder.setAttribute("id", "placeholder");
    placeholder.setAttribute("src", "images/placeholder.gif");
    placeholder.setAttribute("alt", "my image gallery");
    var description = document.createElement("p");
    description.setAttribute("id", "description");
    var desctext = document.createTextNode("Choose an image");
    description.appendChild(desctext);
    var gallery = document.getElementById("imagegallery");
    insertAfter(description, gallery);
    insertAfter(placeholder, description);
}
function showPic(whicpic) {
    if (!document.getElementById("placeholder")) return true;
    var source = whicpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src", source);
    if (!document.getElementById("description")) return false;
    if (whicpic.getAttribute("title")) {
        var text = whicpic.getAttribute("title");
    } else {
        var text = "";
    }
    var description = document.getElementById("description");
    if (description.firstChild.nodeType == 3) {
        description.firstChild.nodeValue = text;
    }
    return false;
}
function prepareGallerey() {
    if (!document.getElementById) return false;
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById("imagegallery")) return false;
    var gallery = document.getElementById("imagegallery");
    var links = gallery.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        links[i].onclick = function () {
            return showPic(this);
        }
    }
}
addLoadEvent(preparePlaceholder);
addLoadEvent(prepareGallerey);
function stripeTables() {
    if (!document.getElementsByTagName) return false;
    var tables = document.getElementsByTagName("table");
    for (var i = 0; i < tables.length; i++) {
        var odd = false;
        var rows = tables[i].getElementsByTagName("tr");
        for (var j = 0; j < rows.length; j++) {
            if (odd == true) {
                addClass(rows[j], "odd");
                odd = false;
            } else {
                odd = true;
            }
        }
    }
}
function highlightRows() {
    if (!document.getElementsByTagName) return false;
    var rows = document.getElementsByTagName("tr");
    for (var i = 0; i < rows.length; i++) {
        rows[i].oldclassName = rows[i].className;
        rows[i].onmouseover = function () {
            addClass(this, "highlight");
        }
        rows[i].onmouseout = function () {
            this.className = this.oldclassName;
        }
    }
}
function displayAbbreviations() {
    if (!document.getElementsByTagName || !document.createElement || !document.createTextNode) return false;
    var abbreviations = document.getElementsByTagName("abbr");
    if (abbreviations.length < 1) return false;
    var defs = new Array();
    for (var i = 0; i < abbreviations.length; i++) {
        var current_abbr = abbreviations[i];
        if (current_abbr.childNodes.length < 1) continue;
        var definition = current_abbr.getAttribute("title");
        var key = current_abbr.lastChild.nodeValue;
        defs[key] = definition;
    }
    var dlist = document.createElement("dl");
    for (key in defs) {
        var definition = defs[key];
        var dtitle = document.createElement("dt");
        var dtitle_text = document.createTextNode(key);
        dtitle.appendChild(dtitle_text);
        var ddesc = document.createElement("dd");
        var ddesc_text = document.createTextNode(definition);
        ddesc.appendChild(ddesc_text);
        dlist.appendChild(dtitle);
        dlist.appendChild(ddesc);
    }
    if (dlist.childNodes.length < 1) return false;
    var header = document.createElement("h3");
    var header_text = document.createTextNode("Abbreviations");
    header.appendChild(header_text);
    var container = document.getElementById("content");
    container.appendChild(header);
    container.appendChild(dlist);
}
addLoadEvent(stripeTables);
addLoadEvent(highlightRows);
addLoadEvent(displayAbbreviations);
function focusLabels() {
    if (!document.getElementsByTagName) return false;
    var labels = document.getElementsByTagName("labels");
    for (var i = 0; i < labels.length; i++) {
        if (labels[i].getAttribute("for")) continue;
        labels[i].onclick = function () {
            var id = this.getAttribute("for");
            if (!document.getElementById(id)) return false;
            var element = document.getElementById(id);
            element.focus();
        }
    }
}
addLoadEvent(focusLabels)
function resetFields(whichform) {
    // if(Modernizr.input.placeholder) return;
    for (var i = 0; i < whichform.elements.length; i++) {
        var element = whichform.elements[i];
        if (element.type == "submit") continue;
        var check = element.placeholder || element.getAttribute("placeholder");
        if (!check) continue;
        element.onfocus = function () {
            var text = this.placeholder || this.getAttribute("placeholder");
            if (this.value == text) {
                this.className = "";
                this.value = "";

            }
        }
        element.onblur = function () {
            if (this.value == "") {
                this.className == "placeholder";
                this.value = this.placeholder || this.getAttribute("placeholder");
            }
        }
        element.onblur();
    }
}
function isFilled(field) {
    if (field.value.replace(" ", "").length == 0) return false;
    var placeholder = field.placeholder || field.getAttribute("placeholder");
    return (field.value != placeholder);
}
function isEmail(field) {
    return (field.value.indexOf("@") != -1 && field.value.indexOf(".") != -1);
}
function validateForm(whicform) {
    for (var i = 0; i < whicform.elements.length; i++) {
        var element = whicform.elements[i];
        if (element.required == "required") {
            if (!isFilled(element)) {
                alert("please fill in the" + element.name + "field");
                return false;
            }
        }
        if (element.type == "email") {
            if (!isEmail(element)) {
                alert("the" + element.name + "field must be a valid email address")
                return false;
            }
        }
    }
    return true;
}
function prepareForms() {
    for (var i = 0; i < document.forms.length; i++) {
        var thisForm = document.forms[i];
        resetFields(thisForm);
        thisForm.onsubmit = function () {
            return validateForm(this);
        }
    }
}
addLoadEvent(prepareForms);
function getHTTPObject() {
    if (typeof XMLHttpRequest == "undefined")
        XMLHttpRequest = function () {
            try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
            catch (e) { }
            try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
            catch (e) { }
            try { return new ActiveXObject("Msxml2.XMLHTTP"); }
            catch (e) { }
            return false;
        }
    return new XMLHttpRequest();
}

function displayAjaxLoading(element) {
    while (element.hasChildNodes()) {
        element.removeChild(element.lastChild);
    }
    var content = document.createElement("img");
    content.setAttribute("src", "images/loading.gif");
    content.setAttribute("alt", "Loading...");
    element.appendChild(content);
}

function submitFormWithAjax(whichform, thetarget) {
    // 调用displayAjaxLoading函数,删除目标元素的子元素,并添加loading.gif图像
    // 把表单的值组织成URL编码的字符串,以便通过Ajax请求发送
    // 创建方法为POST的Ajax请求,把表单的值发送给submit.html
    // 如果请求成功,解析响应并在目标元素中显示结果
    // 如果请求失败,显示错误消息
    var request = getHTTPObject();
    if (!request) { return false; }
    displayAjaxLoading(thetarget);
    var dataParts = [];
    var element;
    for (var i = 0; i < whichform.elements.length; i++) {
        element = whichform.elements[i];
        // 将表单元素拼成URL中传递的信息,同时对表单元素的值进行了适用于URL的转码
        dataParts[i] = element.name + '=' + encodeURIComponent(element.value);
    }
    // 将数组内容拼接起来
    var data = dataParts.join('&');
    // 发起异步POST方式的访问
    request.open('POST', whichform.getAttribute("action"), true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.onreadystatechange = function () {
        // 当访问请求处理完成,接收响应也完成后
        if (request.readyState == 4) {
            if (request.status == 200 || request.status == 0) {
                // 注意下面正则中使用了捕获组的定义
                var matches = request.responseText.match(/
([\s\S]+)<\/article>/); if (matches.length > 0) { // 匹配结果是一个数组,第一个数组元素是与整个模式完整匹配的部分 // 匹配结果数组的第二个元素(索引为1),是responseText中与捕获组中的模式匹配的部分。 // 因为本例中只定义了一个捕获组,所以matches也只包含两个元素。 thetarget.innerHTML = matches[1]; } else { thetarget.innerHTML = '

Oops, there was an error. Sorry.

'
; } } else { thetarget.innerHTML = '

' + request.statusText + '

'
; } } }; request.send(data); return true; };

你可能感兴趣的:(JavaScript,javascript,html,html5)