Javascript :FF and Chrome and IE dynamic loading elements of the difference
- 2020-03-30 01:28:46
- OfStack
<!doctype html>
<html>
<head>
<title>ff with ie The difference between dynamically loading elements </title>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<style type="text/css">
li{margin:0;padding:0;list-style:none}
</style>
<script type="text/javascript">
function add(){
var liTemplate = $("#template");
liTemplate.find("input[name='awbpre']").val("999");
liTemplate.find("input[name='awbno']").val("12312311");
$("#box").append("<li>" + liTemplate.html() + "</li>");
}
</script>
</head>
<body>
<ul id="box">
<li id="template" style="display:none">
awbpre:
<input type="text" value="#awbno#" name="awbpre"/>
awbno:
<input type="text" value="#awbno#" name="awbno"/>
</li>
</ul>
<input type="button" value="add" onclick="return add()"/>
</body>
</html>
When the Add button is clicked, two input fields are added to the page dynamically, and two new input fields are assigned values. IE 6,7,8,9(compatibility mode) runs normally, see the following screenshot:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201401/20140126091800.png ">
But in FF,Chrome,IE9(incompatibility mode), this is not true:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201401/20140126092858.png ">
Change the add() method to
<script type="text/javascript">
function add(){
var liTemplate = $("#template");
$("#box").append("<li>" + liTemplate.html() + "</li>")
var new_li = $("#box li:last");
new_li.find("input[name='awbpre']").val("999");
new_li.find("input[name='awbno']").val("12312311");
}
</script>
Just by the way, The difference between the two is: The first is to do the assignment first and then add it to the dom tree. The second way to write it is to add it to the dom tree and then find the corresponding processing assignment. I'm really new to front-end technology, Personal understanding: The first is similar to "pass by value", var liTemplate = $("#template"); After that, no matter what you do with the elements in liTemplate, because liTemplate has not been added to the dom tree, when you finally call litemplate.html (), the returned HTML code is still the HTML code before the original processing (a little bit by value, using a copy, no matter how you handle it, not affecting the original value); In the second way, when the element is first added to the dom tree and then found from the dom, it is equivalent to the pointer reference of the obtained object. Any modification of the object pointed to by the "pointer" will directly affect the object itself.