Professional JS(10.1.4--end)剩余类型&DOM操作技术&黑画--一百年后的编程语言

1.The Text Type[3]
①Text nodes are represented by the Text type and contain plain text(纯文本) that is interpreted literally and may contain escaped HTML characters(转义后的HTML字符) but no HTML code.

②A Text node has the following characteristics:
a)nodeType is 3.
b)nodeName is “#text”
c)nodeValue is text contained in the node.
d)parentNode is an Element.
e)Child nodes are not supported.

③The following methods allow for manipulation of the text in the code:
a)appendData(text)—-Appends text to the end of the node.
b)deleteData(offset(抵掉),count)—-Deletes count number of characters starting at position offset.
c)insertData(offset,text)—Inserts text at position offset.
d)replaceData(offset,count,text)—Replaces the text starting at offset through offset+count with text.
e)splitText(offset)—Splits the text node into two text nodes separated at position offset.
f)substringData(offset,count)—Extracts(提取) a string from the text beginning at position offset and continuing until offset+count.
g)In addtion to these methods,the length property returns the number of characters in the node.This value is the same as using nodeValue.length or data.length.

+④

<div>Hello World!</div>

var div=document.getElementsByTagName('div');
var textNode=div.firstChild;//来获得div元素中的文本子节点,也可以用div.childNodes[0]
//在获得文本节点的引用后,就可以这样改变它的值
textNode.nodeValue='some other message';

+⑤As long as the node is currently in the document tree,the changes to the text node will be reflected immediately.Another note about changing the value of a text node is that the string is HTML- or XML-encoded(编码)(depending on the type of document),meaning that any less-than'<' symbol,greater-than'>' symobols,or quatation' " ' marks are escaped(转义).

//输出结果是:"some &lt;strong&gt;other&lt;/strong&gt; message"
div.firstChild.nodeValue="some <strong>other</strong> message";

⑥The text type constructor and prototype are accessible in script in Internet Explorer 8,Firefox,Safari,Chrome and Opera.

2.Creating Text Nodes
+①New text nodes can be created using the document.createTextNode() method,which accepts a single argument—-the text to be inserted into the node.As with setting the value of an existing text node,the text will be HTML- or XML-encoded.

var textNode=document.createTextNode("<strong>Hello</strong> world.");

@②
这里写图片描述
③When a text node is added as a sibling of another text node,the text in those nodes is displayed without any space between them.

3.Normalizing Text Nodes(规范化的文本节点)
+①When normalize() is called on a parent of two or more text nodes,those nodes are merged into(合并成) one text node whose nodeValue is equal to the concatenation of the nodeValue properties of each text node.

var element=document.createElement('div');
var textNode=document.createTextNode('Hello world!');
var anotherTextNode=document.createTextNode('yyc.');
element.appendChild(textNode);
element.appendChild(anotherTextNode);
document.body.appendChild(element);
alert(element.childNodes.length);//2
element.normalize();
alert(element.childNodes.length);//1
alert(element.firstChild.nodeValue);//"Hello world!yyc."

②The normalize() method cause Internet Explorer 6 to crash(奔溃) in certain circumstances.Though unconfirmed(未经证实的),this may have been fixed in later patches(补丁) to Internet Explorer 6.This problem doesn't occur in Internet Explorer 7+.

4.Splitting Text Nodes
+①splitText()

var element=document.createElement('div');
var textNode=document.createTextNode('Hello world.');
element.appendChild(textNode);
document.body.appendChild(element);
var newNode=element.firstChild.splitText(5);
alert(element.firstChild.nodeValue);//"Hello"
alert(newNode);//[object Text]
alert(newNode.nodeValue);//" world."----注意空格--包含第五个字符
alert(element.childNodes.length);//2

5.The Comment Type[8]
①Comments are represented in the DOM by the Comment type.A Comment node has the following characteristics:
a)nodeType is 8.
b)nodeName is “#comment”.
c)nodeValue is the content of the comment.
d)parentNode is a Document or Element.
e)Child nodes are not supported.

@@②The Comment type inherits from the same base as the Text type,so it has all of the same string-manipulation(字符串操作) methods except splitText().Also similar to the Text type,the actual content of the comment may be retrieved(获取) using either nodeValue or the data property.
这里写图片描述

这里写图片描述

*注:上面的div元素中存在三个子节点:两个文本节点(空白符)+一个注释节点。

③Comment nodes can be also created using the document.createComment() method and passing in the comment text.

④The Comment type constructor and prototype are accessible in Firefox,Safari,Chrome, and Opera.The Internet Explorer 8 comment nodes are considered to be elements with a tag name of “!”.This means comment nodes can be returned by getElementsByTagName().Internet Explorer 9 represents comments via a custom(自定义的) constructor called HTMLCommentElement even though it doesn't treat comments as elements.

6.The CDATASection Type[4]
①CDATA sections are specific(特有的) to XML-based documents and are represented by the CDATASection type.Similar to Comment,the CDATASection type inherits from the base Text type,so it has all of the same string manipulation methods except for splitText().A CDATASection node has the following characteristics:
a)nodeType is 4.
b)nodeName is “#cdata-section”.
c)nodeValue is the contents of the CDATA section.
d)parentNode is a Document or Element.
e)Child nodes are not supported.

@②CDATA sections are valid only in XML documents,so most browsers will incorrectly parse(解析) a CDATA section into either a Comment or an Element.
这里写图片描述

③True XML documents allow the creation of CDATA sections using document.createCDataSection() and pass in the node's content.

④The CDATASection type constructor and prototype are accessible in Firefox,Safari,Chrome and Opera.Internet Explorer through version 9 still does not support this type.

7.The DocumentType Type[10]
①The DocumentType type is not used very often in web browsers and is supported in only Firefox,Safari,Opera and Chrome 4+.A DocumentType object contains all of the information about the document's doctype and has the following characteristics:
a)nodeType is 10.
b)nodeName is the name of the doctype
c)nodeValue is null.
d)parentNode is a Document.
e)Child nodes are not supported.

②Internet Explorer 8- did not support the DocumentType type,so document.doctype is always null.Furthermore,these browsers misinterpret the doctype as a comment and actually create a comment node for it.Internet Explorer 9 properly(正确地) assigns an object to document.doctype but still does not expose(访问) the DocumentType type.

8.The DocumentFragment Type(文档片段类型)[11]
①Of all the node types,the DocumentFragment type is the only one that has no representation in markup(标记).The DOM defines a document fragment(文段片段) as a “lightweight” document,capable of containing and manipulating(操作) nodes without all of the addtional overhead(占用的资源) of a complete document.DocumentFragment nodes have the following characteristics:
a)nodeType is 11.
b)nodeName is “#document-fragment”.
c)nodeValue is null.
d)parentNode is null.
e)Child nodes may be Element,ProcessingInstruction,Comment,Text,CDATASection,or EntityReference.

②A document fragment cannot be added to a document directly.Instead,it acts as a repository(仓库) for other nodes that may need to be added to the document.Document fragments are created using the document.createDocumentFragment() method,showed here:

var fragment=document.createDocumentFragment();

@③If a node from the document is added to a document fragment,that node is removed from the document tree and won't be rendered(显示) by the browser.The contents of a document fragment can be added to a document via appendChild() or insertBefore().When a document fragment is passed in as an argument to either of these methods,all of the document fragment's child nodes are added in that spot;the document fragment itself is never added to the document tree.
这里写图片描述

9.The Attr Type[Attribute_node-2]
①Element attributes are represented by the Attr type in the DOM.The attr type constructor and prototype are accessible in all browsers,including internet Explorer beginning with version 8.Technically,attributes are nodes that exist in an element's attributes property.Attributes nodes have the following characteristics:
a)nodeType is 2.
b)nodeName is the attribute name.
c)nodeValue is the attribute value.
d)parentNode is null.
e)Child nodes are not supported in HTML.
f)Child nodes may be Text or EntityReference in XML.

②Even though they are nodes,attributes are not considered part of the DOM document tree.Attribute nodes are rarely referenced(参考) directly,with most developers favoring the use of getAttribute(),setAttribute(),removeAttribute().

③There are three properties on an Attr object:name,which is the attribute name(same as nodeName);value,which is the attribute value(same as nodeValue);and specified,which is a Boolean value indicating if the attribute was specified in code or if it is a default value(默认值).

+④New attribute nodes can be created by using document.createAttribute() and passing in the name of the attribute.

//创建一个新的特性节点,并复制给变量attr
var attr=document.createAttribute('align');
attr.value='left';
//将新创建的特性添加到元素中
element.setAttribute(attr);
//attributes属性返回对应特性的Attr节点
alert(element.attributes['align'].value);//"left"
//同上,返回节点
alert(element.getAttributeNode('align').value);//"left"
//getAttribute()返回特性的值
alert(element.getAttribute('align'));//"left"

⑤There is really not a good reason to access(访问) attribute nodes directly.The getAttribute().setAttribute(), and removeAttribute() method are preferable over manipulating attribute nodes.

10.Dynamic Scripts
+①Pulling in an external file.

<script type="text/javascript" src="client.js"></script>

var script=document.createElement('script');
script.type="text/javascript";
script.src="client.js";
document.body.appendChild(script);


//上面的过程可以用一个函数来封装----就是为了避免重复操作---真实的目的:偷懒
function loadScript(url){
    var script=document.createElement('script');
    script.type='text/javascript';
    script.src=url;
    document.body.appendChild(script);
}
//调用这个函数来实现加载外部的js文件
loadScript('client.js');

+②Inserting text directly

<script type="text/javascript">
    function sayHi(){
        alert('Hi');
    }
</script>

//从逻辑上来说,下面的代码是生效的
var script=document.createElement('script');
script.type='text/javascript';
script.appendChild(document.createTextNode("function sayHi(){alert('Hi');}"));
document.body.appendChild(script);


/*
在IE中以上DOM代码会导致错误,因为IE将<script>视为一个特殊的元素,不允许DOM
访问其子节点,不过可以使用<script>元素中的text属性来指定JS代码
*/
//这样的DOM代码可以在IE,Firefox,Opera,Safari 3+运行
var script=document.createElement('script');
script.type='text/javascript';
script.text="function sayHi(){alert('Hi');}";
document.body.appendChild(script);

//Safari 3- 虽然不能正确地支持text属性,但允许使用文本节点技术来指定代码
var script=document.createElement('script');
script.type='text/javascript';
var code="function sayHi(){alert('Hi');}";
try{
    script.appendChild(document.createTextNode(code));
}catch(ex){
    script.text=code;
}
document.body.appendChild(script);

//再封装一下
function loadScriptString(code){
    var script=document.createElement('script');
    script.type='text/javascript';
    //先尝试标准的DOM文本节点方法,除了IE,所有浏览器都支持这种方式
    try{   
        script.appendChild(document.createTextNode(code));
    }catch(ex){
        //弥补IE的不足
        script.text=code;
    }
    document.body.appendChild(script);
}
//用一下,调用一波
loadScriptString("function sayHi(){alert('Hi');}");
//实际上,这样执行代码与全局作用域中把相同的字符串传递给eval()是一样样的

11.Dynamic Styles
①CSS styles are included in HTML pages using one of two elements.The <link> element is used to include CSS from an external file,whereas the <style> element is used to specify inline styles.

+②The <link>element loading styles via an external file is asynchronous,so the styles will load out of order with the JavaScript code being executed.

<link rel="stylesheet" type="text/css" href="styles.css">

//DOM代码
var link=document.createElement('link');
link.rel='stylesheet';
link.type='text/css';
link.href='styles.css';
var head=document.getElementsByTagName('head')[0];
head.appendChild(link);

//封装成函数
function loadStyles(url){
    var link=document.createElement('link');
    link.rel='stylesheet';
    link.type='text/css';
    link.href=url;
    var head=document.getElementsByTagName('head')[0];
    head.appendChild(link);
}
//调用该函数
loadStyles('styles.css');

+③The other way to define styles is using the <style> element and including inline(内联的) CSS.

<style type="text/css">
body{
    background-color:orange;
}
</style>


var style=document.createElement('style');
style.type='text/css';
style.appendChild(document.createTextNode("body{background-color:orange;}"));
var head=document.getElementsByTagName('head')[0];
head.appendChild(style);


var style=document.createElement('style');
style.type='text/css';
var code="body{background-color:orange;}";
try{
    style.appendChild(document.createTextNode(code));
}catch(ex){
    style.stylesheet.cssText=code;//与script.text不同
}
var head=document.getElementsByTagName('head')[0];
head.appendChild(style);

//封装一波
function loadStyleString(code){
    var style=document.createElement('style');
    style.type='text/css';
    try{
        style.appendChild(document.createTextNode(code));
    }catch(ex){
        style.stylesheet.cssText=code;
    }
    var head=document.getElementsByTagName('head')[0];
    head.appendChild(style);
}
//调用一波
loadStyleString("body{background-color:orange;}");

④If you're coding for Internet Explorer specifically,be careful using styleSheet.cssText.If you reuse the same <style> element and try to set this property more than once,it has a tendency(趋势) to crash the browser.Also,setting cssText to the empty string has the potential to crash the browser as well.This is a bug in the browser that hopefully will be fixed in the future.

12.Manipulating Tables
@@①
这里写图片描述

这里写图片描述

13.Using NodeLists
+①The first part of this code gets an HTMLCollection of all <div> elements in the document.Since that collection is "live",any time a new <div> element is added to the page,it gets added into the collection.Since the browser doesn't want to keep a list of all the collections that were created,the collection is updated only when it is accessed again.This creates an interesting problem in terms of(用…的话) a loop such as the one in this example.Each time through the loop,the condition i<divs.length is being evaluated(求值).That means the query to get all <div> elements is being run.Because the body of the loop creates a new <div> element and adds it to the document,the value of divs.length increments each time through the loop;thus i will never equal divs.length since both are being incremented.

//get an HTMLCollection of all <div> elements in the document
var divs=document.getElementsByTagName('div');
var i,div;
for(i=0;i<divs.length;i++){
    div=document.createElement('div');
    document.body.appendChild(div);
}

+②Any time you want to iterate(迭代) over a NodeList,it's best to initialize a second variable with the length and then compare the iterator(迭代器) to that variable.In this example,a second variable,len,is initialized.Since len contains a snapshot(快照) of divs.length at the time the loop began,it prevents the infinite loop that was experienced in the previous example.

var divs=document.getElementsByTagName('div');
var i,div,len;
for(i=0,len=divs.length;i<len;i++){
    div=document.createElement('div');
    document.body.appendChild(div);
}

14.Summary
**①The Document Object Model(DOM) is a language-independent(与语言无关的) API for accessing(访问) and manipulating(操作) HTML and XML documents.DOM Level 1 deals with representing HTML and XML documents as a hierarchy(分层的) of nodes that can be manipulated to change the appearance and structure of the underlying(底层的) documents using JavaScript.

二.黑客与画家-11.一百年后的编程语言
1.一百年后,人们使用是什么语言开发软件?
2.编程语言的进化与生物学进化还是有一定区别的,因为不同分支的语言会发生聚合。【形式有限、突变不是随机的—-借鉴】
3.一种语言的内核设计得越小、越干净,它的生命力就越顽强。
4.随着技术的发展,每一代人都在做上一代人觉得是浪费的事情。【长途电话】
5.新增的运算能力会被糟蹋掉。
6.浪费可以分为好的浪费和坏的浪费。
7.什么时候可以放弃一些性能,换来一点点便利性的提高。
8.语言的语义和语言的实现予以分离。
9.如果一股不可抗拒的力量遇到了一个不可移动的物体,会发生什么?—-时代的选择
10.性能分析器(profiler)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值