码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 动态创建标记与Ajax

时间:2015-01-13 14:24:25      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:javascript   ajax   xmlhttprequest   异步   asynchronous   

JavaScript 动态创建标记与Ajax

 

一:简介

   

        前面都是针对已经存在的标记进行操作、JavaScript同样可以动态创建标记并且与现有标记组合生成新的Document。同时简单的介绍了Ajax。

 

二:动态创建标记与组合

 

        相关方法:

 

/**
 * Some old-shcool method
 */
document.write("str");
var node = document.getElementById('id');

var htmlValue = node.innerHTML;
node.innerHTML = htmlValue;

/**
 * DOM methods
 */
var parent = document.getElementById('id');
var node = document.createElement(nodeName);
parent.appendChild(node);

var txt = document.createTextNode("hello world");
para.appendChild(txt);

/**
 * example : <p>This is <em>my</em> content.</p>
 */
//1. create p and p's children elements
var p = document.createElement("p");
var txt1 = document.createTextNode("This is");
var em = document.createElement("em");
var txt2 = document.createTextNode("content.");

//2. create em's child element
var txt3 = document.createTextNode("my");

//Assemble them
p.appendChild(txt1);
p.appendChild(em);
p.appendChild(txt2);
em.appendChild(txt3);

/**
 * insertBefore
 */
parentElement.insertBefore(newElement, targetElement);

/**
 * insertAfter,without exiting method, custom create
 */
function insertAfter (newElement, targetElement) {
	var parentNode = targetElement.parentNode;
	if (parentNode.lastChild == targetElement){
		parentNode.appendChild(newElement);
	} else {
		parentNode.insertBefore(newElement, targetElement.nextSibling);
	}
}

三:Ajax

   

        Ajax(Asynchronous JavaScript And XML)异步JavaScript和XML、用于对页面请求以异步方式与服务器进行交互进而达到局部刷新页面的效果。

        Ajax实现过程:

 

/**
 * Ajax
 * 1. create request -- XMLHTTPObject
 * 2. request.open("methodType", url, isAsynchronously);
 * 3. request.onreadystatechange = function(){ //key request.readyState == 4}
 * 4. request.send(parameter);
 *
 * request.readyState have five possible values:
 * 0 : uninitialized
 * 1 : loading
 * 2 : loaded
 * 3 : interactive
 * 4 : complete
 */
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 false;
    }
    return new XMLHttpRequest();
}

function getNewContent() {
    var request = getHTTPObject();
    if (request) {
        request.open("GET", "example.txt", true);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                var para = document.createElement("p");
                var txt = document.createTextNode(request.responseText);
                para.appendChild(txt);
                document.getElementById("new").appendChild(para);
            }
        };
        request.send(null); 
    }
}

四:完善图片库

 

        动态创建用于显示默认图片和指定链接的图片和title相关标记——showPicture.js:

/**
 * Attach onclick even on a link tag.
 */
function prepareGallery () {
	if (!document.getElementById) { return false }
	if (!document.getElementsByTagName) {return false}

	var imageGalleryNode = document.getElementById('imageGallery');
	if (!imageGalleryNode) {return false}

	var links = imageGalleryNode.getElementsByTagName("a");
	if (links.length > 0) {
		for (var i = links.length - 1; i >= 0; i--) {
			links[i].onclick = function (){
				/*
					if show picture work then stop a link active.
					a link will not work if return false.
				 */
				return showPicture(this) ? false : true;
			};
			links[i].onkeypress = links[i].onclick;
		}
	}
}

/**
 * Insert after the specified node
 */
function insertAfter (newNode, targetElement) {
	var parentNode = targetElement.parentNode;
	if (parentNode.lastChild == targetElement) {
		parentNode.appendChild(newNode);
	} else {
		parentNode.insertBefore(newNode, targetElement.nextSibling);
	}
}

/**
 * Construct placeholder element
 */
function preparePlaceholder () {

	if (!document.createElement) { return false; }
	if (!document.createTextNode) { return false; }
	if (!document.getElementById){ return false; }
	if (!document.getElementById('imageGallery')) { return false; }
	var imgElement = document.createElement("IMG");
	imgElement.src = "../picture/benchi.jpg";
	imgElement.alt =  "my image gallery";
	imgElement.id = "placeholder";

	var pElement = document.createElement("p");
	pElement.id = "description";

	var txt = document.createTextNode("Choose one picture !");

	var galleryNode = document.getElementById('imageGallery');
	insertAfter(imgElement, galleryNode);
	pElement.appendChild(txt);
	insertAfter(pElement, imgElement);
}

/**
 * Show the clicked picture.
 * which picture is clicked.
 * false if something is unexpected .
 */
function showPicture(whichPicture){
	var placeholder = document.getElementById('placeholder');
	if (!placeholder) {return false}
	if (placeholder.nodeName != "IMG") {return false}

	var source = whichPicture.getAttribute('href');
	placeholder.setAttribute('src', source);

	var description = document.getElementById('description');
	if (description) {
		var text = whichPicture.getAttribute('title') ? whichPicture.getAttribute('title') : "";
		var firstChildNode = description.firstChild;
		if (firstChildNode.nodeType == 3) {
			firstChildNode.nodeValue = text;
		}
	}
	return true;
}

/**
 * Multiple execute window.onload;
 */
function addEvent(fun){
	var oldFunction = window.onload;
	if (!oldFunction) {
		window.onload = fun;
	} else {
		window.onload = function () {
			oldFunction();
			fun();
		}
	}
}

addEvent(prepareGallery);
addEvent(preparePlaceholder);


JavaScript 动态创建标记与Ajax

标签:javascript   ajax   xmlhttprequest   异步   asynchronous   

原文地址:http://blog.csdn.net/crave_shy/article/details/42675607

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!