Dynamic Script We can insert javascript code into the page by using the 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. </p> <p>Dynamically loaded external JavaScript code can be executed immediately, such as the following code: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var script = document.createElement("script"); script.type = "text/javascript"; script.src = "demo.js"; document.body.appendChild(script);</pre><div class="contentsignin">Copy after login</div></div> </div> <p style="text-align: center"><img id="theimg" alt="" baiduimageplusrect="null" baiduimageplusstatus="2" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128142815466.jpg?2015118143325" /></p> <p>As you can see from the results above, the above code generates a <script> node in the <body> element: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> <script type="text/javascript" src="demo.js"> Copy after login It should be noted that the external script file will not be downloaded before the last line of code is executed to add to the page. </p> <p>Another way to specify JavaScript code is inline, for example: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var script = document.createElement("script"); script.type = "text/javascript"; script.appendChild(document.createTextNode("function fn1(){alert('hello wolrd!')} fn1();")); document.body.appendChild(script); </pre><div class="contentsignin">Copy after login</div></div> </div> <p style="text-align: center"><img id="theimg" alt="" baiduimageplusrect="null" baiduimageplusstatus="2" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128143006554.jpg?2015118143027" /></p> <p>The above code will insert a piece of JavaScript code in the <body> element: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> <script type="text/javascript"> function fn1(){alert('hello wolrd!')} fn1(); Copy after login 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 element as a special element and do not allow DOM to access its child nodes. However, JavaScript code can be specified using the text attribute of the <script> element, for example: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var script = document.createElement("script"); script.type = "text/javascript"; script.text("function fn1(){alert('hello wolrd!')} fn1();"); document.body.appendChild(script); </pre><div class="contentsignin">Copy after login</div></div> </div> <p>After modifying the code as above, it can run in IE, Firefox, Safari3.0, Chrome and Opera browsers. 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 code like this: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var script = document.createElement("script"); script.type = "text/javascript"; var code = "function fn1(){alert('hello wolrd!')} fn1();"; try{ script.appendChild(document.createTextNode(code)); }catch(e){ script.text = code; }</pre><div class="contentsignin">Copy after login</div></div> </div> <p>The above code first tries the standard DOM text node method, because except for the old version of IE, other browsers 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> <p>We can encapsulate the code for dynamically adding scripts into a function and dynamically load different scripts through different parameters. </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> function loadScript(code){ var script = document.createElement("script"); script.type = "text/javascript"; try{ script.appendChild(document.createTextNode(code)); }catch(e){ script.text = code; } document.body.appendChild(script); } </pre><div class="contentsignin">Copy after login</div></div> </div> <p>To call this function, you can do as follows: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> loadScript("function fn1(){alert('hello wolrd!')}"); </pre><div class="contentsignin">Copy after login</div></div> </div> <p>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> <p><strong><span style="color: #0000ff">Dynamic Style</span></strong></p> <p>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 the <style> element, which is 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> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var link = document.createElement("link"); link.rel = "stylesheet" link.type = "text/css"; link.href = "styles.css"; var head = document.getElementsByTagName("head")[0];</pre><div class="contentsignin">Copy after login</div></div> </div> <p style="text-align: center"><img id="theimg" alt="" baiduimageplusrect="null" baiduimageplusstatus="2" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128143341450.jpg?2015118143357" /></p> <p>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> <p>Another thing to note is 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> <p>Another way to define styles is to use the <style> element to include embedded CSS styles. For example, the following code: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var style = document.createElement("style"); style.type = "text/css"; style.appendChild(document.createTextNode("body{background:#f00;}")); var head = document.getElementsByTagName("head")[0]; head.appendChild(link); </pre><div class="contentsignin">Copy after login</div></div> </div> <p>After the above code is executed, the following nodes can be dynamically added to the <head> element: </p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> <style type="text/css"> background:#f00; </style> </pre><div class="contentsignin">Copy after login</div></div> </div> <p>以上的代码可以在Firefox、Safari、Chrome和Opera浏览器中正常运行,在旧版本的IE浏览器中会报错。旧版本的IE浏览器会将<style>元素看做一个特殊的节点,不允许访问它的子节点。要解决旧版本IE的问题,就是访问元素的styleSheet属性,该属性又有一个cssText属性,可以接受CSS代码。例如下面的代码:</p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var style = document.createElement("style"); style.type = "text/css"; try{ style.appendChild(document.createTextNode("body{background:#f00;}")); }catch(e){ style.styleSheet.cssText = "body{background:#f00;}"; } </pre><div class="contentsignin">Copy after login</div></div> </div> <p>同样,我们也可以将动态添加样式的代码封装到一个函数中,通过不同的参数来动态加载不同的样式。</p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> function loadStyle(code){ var style = document.createElement("style"); style.type = "text/css"; try{ style.appendChild(document.createTextNode(code)); }catch(e){ style.styleSheet.cssText = code; } var head = document.getElementsByTagName("head")[0]; head.appendChild(style); } </pre><div class="contentsignin">Copy after login</div></div> </div> <p><strong><span style="color: #0000ff">JavaScript对表格的操作</span></strong></p> <p>在JavaScript中,为了使我们能够方便的构建表格,HTML DOM为表格的<table>、<tbody>和<tr>提供了一些属性和方法。</p> <p>表格的<table>元素的属性和方法有:</p> <p>caption:保存<caption>元素的引用的指针。<br /> tBodies:是一个<tbody>元素的HTMLCollection。<br /> tFoot:保存<tfoot>元素的引用的指针。<br /> tHead:保存<thead>元素的引用的指针。<br /> rows:是表格中所有行的HTMLCollection。<br /> createTHead():创建<thead>元素,将它放入表格中,并返回其引用。<br /> createTFoot():创建<tfoot>元素,将它放入表格中,并返回其引用。<br /> createCaption():创建<caption>元素,将它放入表格中,并返回其引用。<br /> deleteTHead():删除<thead>元素。<br /> deleteTFoot():删除<tfoot>元素<br /> deleteCaption():删除<caption>元素<br /> deleteRow(pos):删除指定位置的表格行。<br /> insertRow(pos):向rows集合中指定位置插入一行。</p> <p><span style="color: #ff0000"><strong>表格的<tbody>元素的属性和方法有:</strong></span></p> <p><br /> </p> <p>rows:保存着<tbody>元素中行的HTMLCollection。<br /> deleteRow(pos):删除指定位置的表格行。<br /> insertRow(pos):向rows集合中指定位置插入一行。</p> <p><strong><span style="color: #ff0000">表格的<tr>元素的属性和方法有:</span></strong></p> <p>cells:保存着<tr>元素中单元格的HTMLCollection。<br /> deleteCell(pos):删除指定位置的单元格。<br /> insertCell(pos):向cells集合中指定位置插入一个单元格,并返回新插入单元格的引用。</p> <p>使用上面的这些属性和方法,可以使我们轻松的使用JavaScript来创建表格,例如下面的代码:</p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> //创建表格 vatabldocument.createElement("table"); table.borde1; table.widt"100%"; //创建tbody vatboddocument.createElement("tbody"); table.appendChild(tbody); //创建第一个表格行 tbody.insertRow(0); tbody.rows[0].insertCell(0); tbody.rows[0].cells[0].appendChild(document.createTextNode("单元1-1")); tbody.rows[0].insertCell(1); tbody.rows[0].cells[1].appendChild(document.createTextNode("单元2-1")); //创建第二个表格行 tbody.insertRow(1); tbody.rows[1].insertCell(0); tbody.rows[1].cells[0].appendChild(document.createTextNode("单元1-2")); tbody.rows[1].insertCell(1); tbody.rows[1].cells[1].appendChild(document.createTextNode("单元2-2")); //将表格添加到文档中 document.body.appendChild(table) </pre><div class="contentsignin">Copy after login</div></div> </div> <p>使用上面的代码可以动态的在页面中创建一个表格。其中在创建表格行的时候,通过<tbody>元素调用了insertCell()方法,并传入参数0(表示将插入的行放在什么位置上)。执行了这一行代码后,会自动创建一个表格行,并将它插入到<tbody>元素的0位置上,此时就可以通过tbody.rows[0]来引用新插入的行。</p> <p>创建单元格的方式也与创建表格行的方式相同。通过<tr>元素来调用insertCell()方法,并传入要放置单元格的位置。然后就可以通过tbody.rows[0].cells[0]来引用新插入的单元格。</p> <p>关于NodeList</p> <p>理解NodeList和NamedNodeMap、HTMLCollection是从整体上理解DOM的关键所在。这3个集合都是动态的,也就是说,每当文档结构发生了变化,它们始终都会保存最新的信息。从本质上来说,所有的NodeList对象都是在访问DOM文档时实时运行的查询。例如下面的代码会导致死循环的出现:</p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var divs = document.getElementsByTagName("div"); for(var i = 0; i < divs.length; i++){ var div = document.createElement("div"); document.body.appendChild(div); } </pre><div class="contentsignin">Copy after login</div></div> </div> <p>上面的代码首先获取了所有<div>元素的HTMLCollection,保存在一个变量中。由于这个集合是动态的,所以只要有新的<div>被添加到页面中,新的<div>元素就会被添加到这个集合中。这样导致的后果是div.length值是不断变化的,每次循环会在页面中添加一个<div>元素,length的值也会递增。这样i < divs.length条件就永远不会成立,导致死循环的发生。</p> <p>如果我们要迭代一个NodeList,最好将length属性初始化为第二个变量,然后将迭代器和这个变量做比较,例如:</p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> var divs = document.getElementsByTagName("div"); for(var i = 0,len = divs.length; i < len; i++){ var div = document.createElement("div"); document.body.appendChild(div); } </pre><div class="contentsignin">Copy after login</div></div> </div> <p>由于len中保存了divs.length在循环开始时的一个快照,因此会避免死循环情况的发生。</p> <p>更多示例:</p> <div class="jb51code"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;"> function sAlert(str){ var msgw,msgh,bordercolor; msgw=400;//提示窗口的宽度 msgh=100;//提示窗口的高度 titleheight=25 //提示窗口标题高度 bordercolor="#c51100";//提示窗口的边框颜色 titlecolor="#c51100";//提示窗口的标题颜色 var sWidth,sHeight; sWidth=screen.width; sHeight=screen.height; var bgObj=document.createElement("div"); bgObj.setAttribute('id','bgDiv'); bgObj.style.position="absolute"; bgObj.style.top="0"; bgObj.style.background="#cccccc"; bgObj.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75"; bgObj.style.opacity="0.6"; bgObj.style.left="0"; bgObj.style.width=sWidth + "px"; bgObj.style.height=sHeight + "px"; bgObj.style.zIndex = "10000"; document.body.appendChild(bgObj); var msgObj=document.createElement("div") msgObj.setAttribute("id","msgDiv"); msgObj.setAttribute("align","center"); msgObj.style.background="white"; msgObj.style.border="1px solid " + bordercolor; msgObj.style.position = "absolute"; msgObj.style.left = "50%"; msgObj.style.top = "50%"; msgObj.style.font="12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; msgObj.style.marginLeft = "-225px" ; msgObj.style.marginTop = -75+document.documentElement.scrollTop+"px"; msgObj.style.width = msgw + "px"; msgObj.style.height =msgh + "px"; msgObj.style.textAlign = "center"; msgObj.style.lineHeight ="25px"; msgObj.style.zIndex = "10001"; msgObj.style.position = "absolute"; var box=document.getElementById(str); var title=document.createElement("h4"); title.setAttribute("id","msgTitle"); title.setAttribute("align","right"); title.style.margin="0"; title.style.padding="3px"; title.style.background=bordercolor; title.style.filter="progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);"; title.style.opacity="0.75"; title.style.border="1px solid " + bordercolor; title.style.height="18px"; title.style.font="12px Verdana, Geneva, Arial, Helvetica, sans-serif"; title.style.color="white"; title.style.cursor="pointer"; title.onmousedown=function(){startDrag(this,'msgDiv')}; title.onmouseup=function(){stopDrag(this,'msgDiv')}; title.onmousemove=function(){drag('msgDiv')}; var closer=document.createElement("div"); closer.onclick=function(){ CloseReturn(); document.body.appendChild(box); box.style.display = "none"; document.body.removeChild(bgObj); document.getElementById("msgDiv").removeChild(title); document.body.removeChild(msgObj); }; closer.innerHTML="确定"; document.body.appendChild(msgObj); document.getElementById("msgDiv").appendChild(title); document.getElementById("msgTitle").appendChild(closer); box.style.display="inline"; document.getElementById("msgDiv").appendChild(box); ShowReturn(); }</pre><div class="contentsignin">Copy after login</div></div> </div> <p>html dom tree: </p> <p style="text-align: center"><img id="theimg" onclick="window.open(this.src)" src="http://files.jb51.net/file_images/article/201512/2015128143651942.gif?201511814375" baiduimageplusstatus="2" baiduimageplusrect="null" alt=""></p>