Home >Web Front-end >JS Tutorial >Create dynamic Dom based on JavaScript_javascript techniques

Create dynamic Dom based on JavaScript_javascript techniques

WBOY
WBOYOriginal
2016-05-16 15:26:581107browse

Dynamic Script

We can insert javascript code into the page by using the 3f1c4e4b6b16bbbd69b2ee476dc4f83a 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.

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);

As you can see from the results above, the above code generates a 3f1c4e4b6b16bbbd69b2ee476dc4f83a node in the 6c04bd5ca3fcae76e30b72ad730ca86d element:

<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 3f1c4e4b6b16bbbd69b2ee476dc4f83a to the page.

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('hello wolrd!')} fn1();"));
document.body.appendChild(script); 

The above code will insert a piece of JavaScript code in the 6c04bd5ca3fcae76e30b72ad730ca86d element:

<script type="text/javascript">
function fn1(){alert('hello wolrd!')} 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 3f1c4e4b6b16bbbd69b2ee476dc4f83a 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 3f1c4e4b6b16bbbd69b2ee476dc4f83a element, for example:

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

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:

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;
}

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.

We can encapsulate the code for dynamically adding scripts into a function and dynamically load different scripts through different parameters.

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);
} 

To call this function, you can do as follows:

loadScript("function fn1(){alert('hello wolrd!')}"); 

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.

Dynamic Style

There are usually two elements that can include CSS styles into HTML pages: one is the 2cdf5bf648cf2f33323966d7f58a7f3f element, which is used to include files from external sources; the other is the c9ccee2e6ea535a969eb3f532ad9fe89 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:

var link = document.createElement("link");
link.rel = "stylesheet"
link.type = "text/css";
link.href = "styles.css";
var head = document.getElementsByTagName("head")[0];

The above code can run normally in all major browsers. It should be noted that the 2cdf5bf648cf2f33323966d7f58a7f3f element must be added to the 93f0f5c25f18dab9d176bd4f6de5d30e element instead of the 6c04bd5ca3fcae76e30b72ad730ca86d element to ensure consistent behavior in all browsers.

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.

Another way to define styles is to use the c9ccee2e6ea535a969eb3f532ad9fe89 element to include embedded CSS styles. For example, the following code:

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); 

After the above code is executed, the following nodes can be dynamically added to the 93f0f5c25f18dab9d176bd4f6de5d30e element:

<style type="text/css">
background:#f00;
</style> 

以上的代码可以在Firefox、Safari、Chrome和Opera浏览器中正常运行,在旧版本的IE浏览器中会报错。旧版本的IE浏览器会将c9ccee2e6ea535a969eb3f532ad9fe89元素看做一个特殊的节点,不允许访问它的子节点。要解决旧版本IE的问题,就是访问元素的styleSheet属性,该属性又有一个cssText属性,可以接受CSS代码。例如下面的代码:

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;}";
} 

同样,我们也可以将动态添加样式的代码封装到一个函数中,通过不同的参数来动态加载不同的样式。

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); 
} 

JavaScript对表格的操作

在JavaScript中,为了使我们能够方便的构建表格,HTML DOM为表格的f5d188ed2c074f8b944552db028f98a1、92cee25da80fac49f6fb6eec5fd2c22a和a34de1251f0d9fe1e645927f19a896e8提供了一些属性和方法。

表格的f5d188ed2c074f8b944552db028f98a1元素的属性和方法有:

caption:保存63bd76834ec05ac1f4c0ebbeaafb0994元素的引用的指针。
tBodies:是一个92cee25da80fac49f6fb6eec5fd2c22a元素的HTMLCollection。
tFoot:保存06669983c3badb677f993a8c29d18845元素的引用的指针。
tHead:保存ae20bdd317918ca68efdc799512a9b39元素的引用的指针。
rows:是表格中所有行的HTMLCollection。
createTHead():创建ae20bdd317918ca68efdc799512a9b39元素,将它放入表格中,并返回其引用。
createTFoot():创建06669983c3badb677f993a8c29d18845元素,将它放入表格中,并返回其引用。
createCaption():创建63bd76834ec05ac1f4c0ebbeaafb0994元素,将它放入表格中,并返回其引用。
deleteTHead():删除ae20bdd317918ca68efdc799512a9b39元素。
deleteTFoot():删除06669983c3badb677f993a8c29d18845元素
deleteCaption():删除63bd76834ec05ac1f4c0ebbeaafb0994元素
deleteRow(pos):删除指定位置的表格行。
insertRow(pos):向rows集合中指定位置插入一行。

表格的92cee25da80fac49f6fb6eec5fd2c22a元素的属性和方法有:


rows:保存着92cee25da80fac49f6fb6eec5fd2c22a元素中行的HTMLCollection。
deleteRow(pos):删除指定位置的表格行。
insertRow(pos):向rows集合中指定位置插入一行。

表格的a34de1251f0d9fe1e645927f19a896e8元素的属性和方法有:

cells:保存着a34de1251f0d9fe1e645927f19a896e8元素中单元格的HTMLCollection。
deleteCell(pos):删除指定位置的单元格。
insertCell(pos):向cells集合中指定位置插入一个单元格,并返回新插入单元格的引用。

使用上面的这些属性和方法,可以使我们轻松的使用JavaScript来创建表格,例如下面的代码:

//创建表格
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) 

使用上面的代码可以动态的在页面中创建一个表格。其中在创建表格行的时候,通过92cee25da80fac49f6fb6eec5fd2c22a元素调用了insertCell()方法,并传入参数0(表示将插入的行放在什么位置上)。执行了这一行代码后,会自动创建一个表格行,并将它插入到92cee25da80fac49f6fb6eec5fd2c22a元素的0位置上,此时就可以通过tbody.rows[0]来引用新插入的行。

创建单元格的方式也与创建表格行的方式相同。通过a34de1251f0d9fe1e645927f19a896e8元素来调用insertCell()方法,并传入要放置单元格的位置。然后就可以通过tbody.rows[0].cells[0]来引用新插入的单元格。

关于NodeList

理解NodeList和NamedNodeMap、HTMLCollection是从整体上理解DOM的关键所在。这3个集合都是动态的,也就是说,每当文档结构发生了变化,它们始终都会保存最新的信息。从本质上来说,所有的NodeList对象都是在访问DOM文档时实时运行的查询。例如下面的代码会导致死循环的出现:

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

上面的代码首先获取了所有dc6dce4a544fdca2df29d5ac0ea9906b元素的HTMLCollection,保存在一个变量中。由于这个集合是动态的,所以只要有新的dc6dce4a544fdca2df29d5ac0ea9906b被添加到页面中,新的dc6dce4a544fdca2df29d5ac0ea9906b元素就会被添加到这个集合中。这样导致的后果是div.length值是不断变化的,每次循环会在页面中添加一个dc6dce4a544fdca2df29d5ac0ea9906b元素,length的值也会递增。这样i < divs.length条件就永远不会成立,导致死循环的发生。

如果我们要迭代一个NodeList,最好将length属性初始化为第二个变量,然后将迭代器和这个变量做比较,例如:

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

由于len中保存了divs.length在循环开始时的一个快照,因此会避免死循环情况的发生。

更多示例:

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();
}

html dom tree:

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