JS学习笔记第10章DOM操作技术

32次阅读

共计 2236 个字符,预计需要花费 6 分钟才能阅读完成。

1、动态脚本

创建动态脚本有两种方式:插入外部文件和直接插入 Javascript 代码。

  • (1)调用外部文件

    function loadScript(url) {var script = document.createElement("script");
         script.type = "text/javascript";
         script.src = url;
         document.body.appendChild(script);
    }
    
    // 调用以上函数就可以加载外部的 Javascript 文件了
    loadScript("client.js");
  • (2)直接插入 JS 代码

     function loadScriptString(code){var script = document.createElement("script");
         script.type = "text/javascript";
         try {script.appendChild(document.createTextNode(code));
         } catch (ex){script.text = code;  //IE 浏览器}
         document.body.appendChild(script);
     }
     // 下面是调用这个函数的示例
     loadScriptString("function sayHi() {alert('hi');}");
     
    

2、动态样式

能够把 CSS 样式包含到 HTML 页面的元素有两个。其中 <link> 元素用于包含来自外部的文件,而 <style> 元素用于指定嵌入的样式;

  • (1)<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()函数如下所示
    loadStyles("styles.css");
    
  • (2)<style> 元素用于指定嵌入的样式

    function loadStyleString(css){var style = document.createElement("style");
        style.type = "text/css";
        try{style.appendChild(document.createTextNode(css));
        } catch (ex){style.styleSheet.cssText = css;}
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(style);
    }
    
    function addStyle(){loadStyleString("body{background-color:red}"); 
    }
    // 调用这个函数的示例如下
    loadStyleString("body{background-color:red}");

3、操作表格

为了方便构建表格,HTML DOM 为 <table>、<tbody>、<tr> 元素添加了一些属性和方法:

(1)为 <table> 元素添加的属性和方法

(2)为 <tbody> 元素添加的属性和方法

(3)为 <tr> 元素添加的属性和方法

(4)创建表格代码示例

// 创建 table
var table = document.createElement("table");
table.border = 1;
table.width = "100%";

// 创建 tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);

// 创建第 1 行
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("Cell 1,1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("Cell 2,1"));

// 创建第 2 行
tbody.insertRow(1);
tbody.rows[1].insertCell(0);
tbody.rows[1].cells[0].appendChild(document.createTextNode("Cell 1,2"));
tbody.rows[1].insertCell(1);
tbody.rows[1].cells[1].appendChild(document.createTextNode("Cell 2,2"));

// 将表格添加到文档主体中
document.body.appendChild(table);

4、使用 NodeList

NodeList、NamedNodeMap 和 HTMLCollection 这三个集合都是 “动态的”;即每当文档结构有变化时,它们都会得到更新。
一般来说应该尽量减少访问 NodeList 的次数,因为每次访问 NodeList,都会运行一次基于文档的查询。所以,可以考虑将从 NodeList 中取得的值缓存起来。

正文完
 0