DOM常用方法:
- getElementById
- getAttribute
- setAttribute
childNodes[0]:子节点数组的第一个元素,它与firstChild等价
nodeValue:改变文本节点的值
<code><!DOCTYPE html> <html lang="en"> <meta charset="utf-8"> <title>Image Gallery</title> <body> <h1>Snapshots</h1> <ul> <li> <a href="images/fireworks.jpg" title="A fireworks display" onclick="showPic(this);return false;">Fireworks</a> </li> <li> <a href="images/coffee.jpg" title="A cup of black coffee" onclick="showPic(this);return false;">Coffee</a> </li> <li> <a href="images/rose.jpg" title="A red, red rose" onclick="showPic(this);return false;">Rose</a> </li> <li> <a href="images/bigben.jpg" title="The famous clock" onclick="showPic(this);return false;">Big Ben</a> </li> </ul> <img id="placeholder" src="images/placeholder.gif" alt="my image gallery"/> <p id="description">Choose an images</p> <script src="./jas.js"/> </body> </html></code>
<code> window.onload=showNumb; function showPic (whichpic) { var url = whichpic.getAttribute("href"); var title = whichpic.getAttribute("title"); var aElement = document.getElementById("placeholder"); var pElement = document.getElementById("description"); //改变元素节点src属性 aElement.setAttribute("src",url); //改变文本节点内容方式一 //pElement.childNodes[0].nodeValue = title; //改变文本节点内容方式二 pElement.firstChild.nodeValue = title; }</code>
关于平稳退化
html代码:
<code><a href="javascript:popUp('https://baidu.com');">Example</a> <a href="#" onclick="popUp('https://baidu.com');return false;">Example</a></code>
js代码:
<code>function popUp(winUrl){ window.open(winUrl,"my","width=320,height=480"); }</code>
以上两种打开新窗口的方式都不能平稳退化。如果用户已经禁用了浏览器的javascript功能,这样的链接将毫无用处。
比较好的做法是:
<code><a href="https://baidu.com" onclick="popUp(this.href);return false;">Example</a></code>
这样,因为href有了值,就可以平稳退化。即使用户禁用了javascript功能,当搜索引擎蜘蛛过来爬时候,不会受影响,照样可以爬到内容。
最后,其实最佳实践是使用“渐进增强”方法,所谓的“渐进增强”就是用一些额外的信息层去包裹原始数据。在这里,就是分离javascript,如下:
html代码:
<code> <a href="https://baidu.com" class="popup">Example</a></code>
js代码:
<code>function popUp(winUrl){ window.open(winUrl,"my","width=680,height=320"); } function prepareLinks(){ var links = document.getElementsByTagName("a"); for(var i = 0;i<links.length;i++){ if(links[i].getAttribute("class")=="popup"){ links[i].onclick=function(){ popUp(this.getAttribute("href")); return false; } } } }</code>
文章评论