Home  >  Article  >  Web Front-end  >  JavaScript Document Object Model-DOM Operation Technology

JavaScript Document Object Model-DOM Operation Technology

黄舟
黄舟Original
2017-01-20 14:48:501305browse

Dynamic Script

We can insert JavaScript code into the page by using the <script> element in the page. There are two ways: one is to reference an external js file through the src attribute, and the other is to use this element to include a piece of js code. The so-called dynamic script means that the script does not exist when the page is loaded. The script can be added dynamically by modifying the DOM at a certain time in the future. Just like manipulating HTML elements, there are two ways to create dynamic scripts: inserting external files and directly inserting JavaScript code. </script>

Dynamically loaded external JavaScript code can be executed immediately, such as the following code:

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

JavaScript Document Object Model-DOM Operation Technology

As you can see from the results in the above figure, the above code A <script> node is generated in the <body> element: </script>

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

It should be noted that the external script file will not be downloaded before the last line of code is executed to add <script> to the page. of. </script>

Another way to specify JavaScript code is inline, for example:

var script = document.createElement("script");
script.type = "text/javascript";
script.appendChild(document.createTextNode("function fn1(){alert(&#39;hello wolrd!&#39;)} fn1();"));
document.body.appendChild(script);

JavaScript Document Object Model-DOM Operation Technology

##The above code will insert a piece of JavaScript in the element Code:

<script type="text/javascript">
  function fn1(){alert(&#39;hello wolrd!&#39;)} fn1();
</script>

After executing the above code, a prompt box will pop up, displaying the text "hello world!".

In Firefox, Safari, Chrome and Opera browsers, the DOM code operated above can be executed normally. But in older versions of IE browsers, these codes will cause errors. Older versions of IE browsers treat the <script> element as a special element and do not allow DOM to access its child nodes. However, you can use the text attribute of the <script> element to specify JavaScript code, for example: <p><pre class="brush:js;toolbar:false">var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; script.text(&quot;function fn1(){alert(&amp;#39;hello wolrd!&amp;#39;)} fn1();&quot;); document.body.appendChild(script);</pre>After modifying the code as above, it can be used in IE, Firefox, Safari3.0, Chrome and Opera browsers run. Although browsers before Safari 3.0 cannot correctly execute the text attribute, they can use text nodes to specify code. So if you need to support older versions of browsers, you can write the code as follows: <p><pre class="brush:js;toolbar:false">var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; var code = &quot;function fn1(){alert(&amp;#39;hello wolrd!&amp;#39;)} fn1();&quot;; try{ script.appendChild(document.createTextNode(code)); }catch(e){ script.text = code; }</pre>The above code first tries the standard DOM text node method, because in addition to the old version of IE browser, other browsers All support this method. If this line of code throws an exception, it means that it is an old version of IE, and the text attribute must be used. <p>We can encapsulate the code for dynamically adding scripts into a function and dynamically load different scripts through different parameters. <p><pre class="brush:js;toolbar:false">function loadScript(code){ var script = document.createElement(&quot;script&quot;); script.type = &quot;text/javascript&quot;; try{ script.appendChild(document.createTextNode(code)); }catch(e){ script.text = code; } document.body.appendChild(script); }</pre>To call this function, you can look like the following: <p><pre class="brush:js;toolbar:false">loadScript(&quot;function fn1(){alert(&amp;#39;hello wolrd!&amp;#39;)}&quot;);</pre>The code loaded in this way will be executed in the global scope and will be available immediately after the script is executed. In fact, executing the code this way is the same as passing the same string to the eval() function in the global scope. <p> Dynamic Style<p style="box-sizing: border-box; font-family: "Microsoft YaHei", simsun, "Helvetica Neue", Arial, Helvetica, sans-serif; line-height: 1.1; color: rgb(65, 74, 81); margin: 2em 0px 0.25em; font-size: 1.05em; padding: 0.25em 0px; white-space: normal; background-color: rgb(255, 255, 255);">There are usually two elements that can include CSS styles into HTML pages: one is the <link> element, which is used to include files from external sources; the other is &lt ;style> element, used to specify embedded styles. Similar to dynamic scripts, dynamic styles are styles that do not exist when the page loads. Dynamic styles are scripts that are dynamically added to the page after the page has finished loading. For example, the following example: <p><pre class="brush:js;toolbar:false">var link = document.createElement(&quot;link&quot;); link.rel = &quot;stylesheet&quot; link.type = &quot;text/css&quot;; link.href = &quot;styles.css&quot;; var head = document.getElementsByTagName(&quot;head&quot;)[0]; head.appendChild(link);</pre><p><img src="https://img.php.cn//upload/image/354/443/408/1484894834447361.jpg" title="1484894834447361.jpg" alt="JavaScript Document Object Model-DOM Operation Technology"/>The above code can run normally in all major browsers. It should be noted that the <link> element must be added to the <head> element instead of the <body> element to ensure consistent behavior in all browsers. <p> Also note that the process of loading external style files is asynchronous, which means that there is no fixed order in the process of loading styles and executing JavaScript code. <p>Another way to define styles is to use the <style> element to include embedded CSS styles. For example, the following code: <p><pre class="brush:js;toolbar:false">var style = document.createElement(&quot;style&quot;); style.type = &quot;text/css&quot;; style.appendChild(document.createTextNode(&quot;body{background:#f00;}&quot;)); var head = document.getElementsByTagName(&quot;head&quot;)[0]; head.appendChild(link);</pre>After the above code is executed, the following nodes can be dynamically added to the <head> element: <p><pre class="brush:js;toolbar:false">&lt;style type=&quot;text/css&quot;&gt; background:#f00; &lt;/style&gt;</pre><p>以上的代码可以在Firefox、Safari、Chrome和Opera浏览器中正常运行,在旧版本的IE浏览器中会报错。旧版本的IE浏览器会将<style>元素看做一个特殊的节点,不允许访问它的子节点。要解决旧版本IE的问题,就是访问元素的styleSheet属性,该属性又有一个cssText属性,可以接受CSS代码。例如下面的代码:<pre class="brush:js;toolbar:false">var style = document.createElement(&quot;style&quot;); style.type = &quot;text/css&quot;; try{ style.appendChild(document.createTextNode(&quot;body{background:#f00;}&quot;)); }catch(e){ style.styleSheet.cssText = &quot;body{background:#f00;}&quot;; }</pre><p>同样,我们也可以将动态添加样式的代码封装到一个函数中,通过不同的参数来动态加载不同的样式。<pre class="brush:js;toolbar:false">function loadStyle(code){ var style = document.createElement(&quot;style&quot;); style.type = &quot;text/css&quot;; try{ style.appendChild(document.createTextNode(code)); }catch(e){ style.styleSheet.cssText = code; } var head = document.getElementsByTagName(&quot;head&quot;)[0]; head.appendChild(style); }</pre><p style="box-sizing: border-box; font-family: "Microsoft YaHei", simsun, "Helvetica Neue", Arial, Helvetica, sans-serif; line-height: 1.1; color: rgb(65, 74, 81); margin: 2em 0px 0.25em; font-size: 1.05em; padding: 0.25em 0px; white-space: normal; background-color: rgb(255, 255, 255);"> JavaScript对表格的操作<p>在JavaScript中,为了使我们能够方便的构建表格,HTML DOM为表格的<table>、<tbody>和<tr>提供了一些属性和方法。<p>表格的<table>元素的属性和方法有:<ul class=" list-paddingleft-2" style="list-style-type: disc;"><li><p>caption:保存<caption>元素的引用的指针。<li><p>tBodies:是一个<tbody>元素的HTMLCollection。<li><p>tFoot:保存<tfoot>元素的引用的指针。<li><p>tHead:保存<thead>元素的引用的指针。<li><p>rows:是表格中所有行的HTMLCollection。<li><p>createTHead():创建<thead>元素,将它放入表格中,并返回其引用。<li><p>createTFoot():创建<tfoot>元素,将它放入表格中,并返回其引用。<li><p>createCaption():创建<caption>元素,将它放入表格中,并返回其引用。<li><p>deleteTHead():删除<thead>元素。<li><p>deleteTFoot():删除<tfoot>元素<li><p>deleteCaption():删除<caption>元素<li><p>deleteRow(pos):删除指定位置的表格行。<li><p>insertRow(pos):向rows集合中指定位置插入一行。<p>表格的<tbody>元素的属性和方法有:<ul class=" list-paddingleft-2" style="list-style-type: disc;"><li><p>rows:保存着<tbody>元素中行的HTMLCollection。<li><p>deleteRow(pos):删除指定位置的表格行。<li><p>insertRow(pos):向rows集合中指定位置插入一行。<p>表格的<tr>元素的属性和方法有:<ul class=" list-paddingleft-2" style="list-style-type: disc;"><li><p>cells:保存着<tr>元素中单元格的HTMLCollection。<li><p>deleteCell(pos):删除指定位置的单元格。<li><p>insertCell(pos):向cells集合中指定位置插入一个单元格,并返回新插入单元格的引用。<p>使用上面的这些属性和方法,可以使我们轻松的使用JavaScript来创建表格,例如下面的代码:<pre class="brush:js;toolbar:false">//创建表格 var table = document.createElement(&quot;table&quot;); table.border = 1; table.width = &quot;100%&quot;; //创建tbody var tbody = document.createElement(&quot;tbody&quot;); table.appendChild(tbody); //创建第一个表格行 tbody.insertRow(0); tbody.rows[0].insertCell(0); tbody.rows[0].cells[0].appendChild(document.createTextNode(&quot;单元格 1-1&quot;)); tbody.rows[0].insertCell(1); tbody.rows[0].cells[1].appendChild(document.createTextNode(&quot;单元格 2-1&quot;)); //创建第二个表格行 tbody.insertRow(1); tbody.rows[1].insertCell(0); tbody.rows[1].cells[0].appendChild(document.createTextNode(&quot;单元格 1-2&quot;)); tbody.rows[1].insertCell(1); tbody.rows[1].cells[1].appendChild(document.createTextNode(&quot;单元格 2-2&quot;)); //将表格添加到文档中 document.body.appendChild(table);</pre><p>使用上面的代码可以动态的在页面中创建一个表格。其中在创建表格行的时候,通过<tbody>元素调用了insertCell()方法,并传入参数0(表示将插入的行放在什么位置上)。执行了这一行代码后,会自动创建一个表格行,并将它插入到<tbody>元素的0位置上,此时就可以通过tbody.rows[0]来引用新插入的行。<p>创建单元格的方式也与创建表格行的方式相同。通过<tr>元素来调用insertCell()方法,并传入要放置单元格的位置。然后就可以通过tbody.rows[0].cells[0]来引用新插入的单元格。<p style="box-sizing: border-box; font-family: "Microsoft YaHei", simsun, "Helvetica Neue", Arial, Helvetica, sans-serif; line-height: 1.1; color: rgb(65, 74, 81); margin: 2em 0px 0.25em; font-size: 1.05em; padding: 0.25em 0px; white-space: normal; background-color: rgb(255, 255, 255);"> 关于NodeList<p>理解NodeList和NamedNodeMap、HTMLCollection是从整体上理解DOM的关键所在。这3个集合都是动态的,也就是说,每当文档结构发生了变化,它们始终都会保存最新的信息。从本质上来说,所有的NodeList对象都是在访问DOM文档时实时运行的查询。例如下面的代码会导致死循环的出现:<pre class="brush:js;toolbar:false">var divs = document.getElementsByTagName(&quot;div&quot;); for(var i = 0; i &lt; divs.length; i++){ var div = document.createElement(&quot;div&quot;); document.body.appendChild(div); }</pre><p>上面的代码首先获取了所有<div>元素的HTMLCollection,保存在一个变量中。由于这个集合是动态的,所以只要有新的<div>被添加到页面中,新的<div>元素就会被添加到这个集合中。这样导致的后果是div.length值是不断变化的,每次循环会在页面中添加一个<div>元素,length的值也会递增。这样i < divs.length条件就永远不会成立,导致死循环的发生。<p>如果我们要迭代一个NodeList,最好将length属性初始化为第二个变量,然后将迭代器和这个变量做比较,例如:<pre class="brush:js;toolbar:false">var divs = document.getElementsByTagName(&quot;div&quot;); for(var i = 0,len = divs.length; i &lt; len; i++){ var div = document.createElement(&quot;div&quot;); document.body.appendChild(div); }</pre><p>以上就是JavaScript文档对象模型-DOM操作技术的内容,更多相关内容请关注PHP中文网(www.php.cn)!<p><br/></script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn