《JavaScript_DOM编程艺术》Chapter07 动态创建标记,Chapter08 充实文档内容---20210429

Chapter07 动态创建标记

传统技术

document.write

  • document.write的最大缺点是它违背了“行为应该与表现分离”的原则。
    #example.js
function insertParagraph(text){
     
	var str="

"; str += text; str += "

"; document.write(str); }

#HTML

<body>
<script src="example.js">
	<script>
		insertParagraph("This is inserted.");
	script>
body>

innerHTML

innerHTML属性将替换元素中的全部内容,不会返回任何对刚插入的内容的引用。
#example.js

window.onload = function(){
     
	var testdiv = document.getElementById("testdiv");
	testdiv.innerHTML = "

I inserted this content.

"
; }

DOM方法

document.createElement(nodeName)

创建新节点,只要使用该方法,最好把新创建出来的元素赋给一个变量。

parent.appendChild(child)

将节点插入节点树,该方法还可以用来连接那些尚未成为文档树一部分的节点。

document.createTextNode(text)

创建文本节点。

parentElement.insertBefore(newElement,targetElement)

把一个新元素插入到一个现有元素的前面。

DOM本身没有提供inserAfter方法,但可以利用已有的DOM方法和属性编写一个insertAfter函数:

function insertAfter(newElement,targetElement){
     
	var parent = targetElement.parentNode;
	if(parent.lastChild == targetElement){
     
		parent.appendChild(newElement);
	}else{
     
		//把新元素插入到目标元素的下一个兄弟元素之前
		parent.insertBefore(newElement,targetElement.nextSibling);
	}
}

综合运用之图片库的改进

#showPic.js 增加preparePlaceholder()和insertAfter(newElement,targetElement)

function prepareGallery(){
     
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById) 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)? false:true;
        }
        links[i].onkeypress = links[i].onclick;
    }
}


function showPic(whichpic){
     
    if (!document.getElementById("placeholder")) return false;
    var source = whichpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src",source);
    if (document.getElementById("description")){
     
    var text = whichpic.getAttribute("title")? whichpic.getAttribute("title"):"";
    var description = document.getElementById("description");
    if(description.firstChild.nodeType == 3){
     
        description.firstChild.nodeValue = text;
      }
    }
    return true;
}



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 preparePlaceholder(){
     
    //my image gallery
    //

Choose an image.

/*检查是否存在*/ if(!document.createElement) return false; if(!document.createTextNode) return false; if(!document.getElementById) return false; if(!document.getElementById("imagegallery")) return false; /*构建Placeholder*/ 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(placeholder,gallery); insertAfter(description,placeholder); } /*执行加载函数*/ addLoadEvent(preparePlaceholder); addLoadEvent(prepareGallery);

#gallery.html删除placeholder


<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>
            Image Gallery
        title>
        <link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen">
    head>
    <body>
        <h1>Snapshotsh1>
        <ul id="imagegallery">
            <li>
                <a href="images/fireworks.jpg" title="A fireworks display">
                    <img src="images/fireworks.jpg" alt="Fireworks">
                a>
            li>
            <li>
                <a href="images/coffee.jpg" title="A cup of black coffee">
                    <img src="images/coffee.jpg" alt="Coffee">
                a>
            li>
            <li>
                <a href="images/rose.jpg" title="A red,red rose">
                    <img src="images/rose.jpg" alt="Rose">
                a>
            li>
            <li>
                <a href="images/bigben.jpg" title="The famous clock">
                    <img src="images/bigben.jpg" alt="Big Ben">
                a>
            li>
        ul>
        <script src="scripts/showPic.js">script>
    body>
html>

Ajax

#getHTTPObject.js

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();
  }

#addLoadEvent.js

function addLoadEvent(func){
     
	var oldonload = window.onload
	if (typeof window.onload != 'function'){
     
		window.onload = func;
	}
	else{
     
		window.onload = function(){
     
			oldonload();
			func();
		}
	}
}

#getNewContent.js

function getNewContent() {
     
	var request = getHTTPObject();
	if(request){
     
	  request.open("GET","example.txt",true);
	  request.onreadystatechange = function(){
     
		if(request.readyState == 4){
     
		  alert('Response Received');
		  var para = document.createElement("p");
		  var txt = document.createTextNode('Replace response from the example.txt');
		  para.appendChild(txt);
		  document.getElementById('new').appendChild(para);
		}
	  };
	  request.send(null);
	}else {
     
	  alert('Sorry, your browser doesn\'t support XMLHttpRequest');
	}
	  alert('Function Done');
  }
  addLoadEvent(getNewContent);

#ajax.html


<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>
            Ajax
        title>
    head>
    <body>
        <div id="new">div>
        <script src="scripts/addLoadEvent.js">script>
        <script src="scripts/getHTTPObject.js">script>
        <script src="scripts/getNewContent.js">script>
    body>
html>


Chapter08 充实文档内容

用JavaScript函数先把文档结构里的一些现有信息提取出来,再把这些信息以一种清晰和有意义的方式重新插入到文档里。
#explanation.html


<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>
            Emplaining the Document Object Model
        title>
        <link rel="stylesheet" href="styles/typography.css" type="text/css" media="screen">

    head>
    <body>
        <ul id="navigation">
            <li><a href="index.html" accesskey="1">Homea>li>
            <li><a href="search.html" accesskey="4">Searcha>li>
            <li><a href="contact.html" accesskey="9">Contacta>li>
        ul>
        <h1>What is the Document Object Modelh1>
        <p>
            The <abbr title="World Wide Web Consortium">W3Cabbr> defines the <abbr title="Document Object Model"> DOM abbr> as:
        p>
        <blockquote cite="http://www.w3.org/DOM/">
        p>
        <p>A platform and language-neutral interface that will allow programs and scripts to dynamtically access and update the content, structure and style of documents.
        p>
        blockquote>
        <p>
        It is an <abbr title="Application Programming Interface"> API abbr>
          that can be used to navigate <abbr title="HyperText Markup Language">
          HTML abbr> and <abbr title="eXtensible Markup Language">XMLabbr> documents.
        p>
        <script src="scripts/addLoadEvent.js">script>
        <script src="scripts/displayAbbreviations.js">script>
        <script src="scripts/displayCitations.js">script>
        <script src="scripts/displayAccesskeys.js">script>
    body>
html>

综合运用之创建“缩略语列表”

#displayAbbreviations.js

/*显示缩略图*/
function displayAbbreviations() {
     
	/*检查*/
	if (!document.getElementsByName || !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];
		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);
	}
	/*创建标题*/
	var header = document.createElement("h2");
	var header_text = document.createTextNode("Abbreviations");
	header.appendChild(header_text);
	/*添加标题和定义列表到页面主体*/
	document.body.appendChild(header);
	document.body.appendChild(dlist);
  }
  addLoadEvent(displayAbbreviations);

《JavaScript_DOM编程艺术》Chapter07 动态创建标记,Chapter08 充实文档内容---20210429_第1张图片

综合运用之创建“文献来源链接”

#displayCitations.js

/*显示缩略图*/
function displayCitations() {
     
	/*检查*/
	if (!document.getElementsByName || !document.createElement || !document.createTextNode) return false
	/*取得所有缩略词*/
	var quotes = document.getElementsByTagName("blockquote");
	/*遍历*/
	for (var i=0; i<quotes.length; i++){
     
	/*假如没有cite,就继续循环*/
		if (!quotes[i].getAttribute("cite")) continue;
	/*保存cite属性*/
		var url = quotes[i].getAttribute("cite");
	/*取得引用中的所有元素节点*/	
		var quoteChildren = quotes[i].getElementsByTagName("*");
	/*取得最后一个元素节点*/	
		var elem = quoteChildren[quoteChildren.length-1];
	/*创建标记*/
		var link = document.createElement("a");
		var link_text = document.createTextNode("source");
		link.appendChild(link_text);
		link.setAttribute("href",url);
		var superscript = document.createElement("sup");
		superscript.appendChild(link);
	}
	/*把标记添加到引用中的最后一个元素节点*/
	elem.appendChild(superscript);
  }
  addLoadEvent(displayCitations);

《JavaScript_DOM编程艺术》Chapter07 动态创建标记,Chapter08 充实文档内容---20210429_第2张图片

综合运用之创建“快捷键清单”

#displayAccesskeys.js

/*显示缩略图*/
function displayAccesskeys() {
     
	/*检查*/
	if (!document.getElementsByName || !document.createElement || !document.createTextNode) return false
	/*取得文档中的链接*/
	var links = document.getElementsByTagName("a");
	/*创建数组保存访问键*/
	var akeys = new Array();
	/*遍历*/
	for (var i=0; i<links.length; i++){
     
		var current_link = links[i];
	/*假如没有指定属性,就继续循环*/
		if (!current_link.getAttribute("accesskey")) continue;
	/*保存指定属性*/
		var key = current_link.getAttribute("accesskey");
	/*取得链接文本*/	
		var text = current_link.lastChild.nodeValue;
	/*添加到数组*/	
		akeys[key]=text;
	}
	/*创建列表*/
	var list = document.createElement("ul");
	for (key in akeys){
     
		var text = akeys[key];
		var str = key + ":" +text;
		var item = document.createElement("li");
		var item_text = document.createTextNode(str);
		item.appendChild(item_text);
		list.appendChild(item);
	}
	/*创造标题*/
	var header = document.createElement("h1");
	var header_text = document.createTextNode("Accesskeys");
	header.appendChild(header_text);
	/*添加到页面主体*/
	document.body.appendChild(header);
	document.body.appendChild(list);
}

addLoadEvent(displayAccesskeys);

《JavaScript_DOM编程艺术》Chapter07 动态创建标记,Chapter08 充实文档内容---20210429_第3张图片

你可能感兴趣的:(html,js,javascript,dom)