Js related technology
Array in JS: [city]
new Array()
DOM tree operation:
Create node: document.createElement
Create text node: document.createTextNode
Add node: appendChild
requirement analysis
In our registration form, we usually need to know the user's native place, and need an optional key. When the user selects a province, all cities under the province are listed
technical analysis
- Preparation: data of city information
- Add node: appendChild (JS)
a. append: add child elements to the end
$("#div1").append("<font color='red'>this is replacing text</font>")
b. appendTo: find yourself a father and add yourself to someone else's home
$("#div1").prepend("<font color='red'>this is replacing text</font>")
Same as the first one
c. prepend: add before child element
$("#div1").after("<font color='red'>this is replacing text</font>")
d. after: add a brother after your own
$("<font color='red'>this is replacing text</font>").appendTo("#div1")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="js/jquery-1.11.0.js"></script> <script> $(function () { $("#btn1").click(function () { // $("#div1").append("<font color='red'>this is replacing text</font>") // $("#div1").prepend("<font color='red'>this is replacing text</font>") $("#div1").after("<font color='red'>this is replacing text</font>") // $("<font color='red'>this is replacing text</font>").appendTo("#div1") }); }); </script> </head> <body> <input type="button" value="click me, replace text" id="btn1"> <div id="div1">this is a text that will be replaced!</div> </body> </html>
- Traversal operation:
<script> var cities = ["Shenzhen City", "Dongguan City", "Huizhou City", "Guangzhou City"]; $(cities).each(function (i, n) { console.log(i + "====" + n); }) $.each(cities, function (i, n) { console.log(i + ">>>>" + n); }) </script>
Step analysis:
- Files imported into JQ
- Document load event: page initialization
- Further identify the event: change event
- Function: get the currently selected province
- Get city, traverse city data
- Add the traversed city to the city's select
Code implementation:
$(function(){ $("#province").change(function(){ // alert(this.value); //Get city information var cities = provinces[this.value]; //Clear option s in City select /*var $city = $("#city"); //Convert JQ object to JS object var citySelect = $city.get(0) citySelect.options.length = 0;*/ $("#city").empty(); / / empty by JQ //Traverse City data $(cities).each(function(i,n){ $("#city").append("<option>"+n+"</option>"); }); }); });