JQuery省市聯動效果實現過程詳解
Js相關技術
JS中的數組: ["城市"]
new Array()
DOM樹操作:
- 創(chuàng)建節(jié)點: document.createElement
- 創(chuàng)建文本節(jié)點: document.createTextNode
- 添加節(jié)點: appendChild
需求分析
在我們的注冊表單中,通常我們需要知道用戶的籍貫,需要一個給用選擇的項,當用戶選中了省份之后,列出省下面所有的城市
技術分析
準備工作 : 城市信息的數據
添加節(jié)點 : appendChild (JS)
a. append : 添加子元素到末尾
$("#div1").append("<font color='red'>this is replacing text</font>")
b. appendTo : 給自己找一個爹,將自己添加到別人家里
$("#div1").prepend("<font color='red'>this is replacing text</font>")
和第一個效果一樣
c. prepend : 在子元素前面添加
$("#div1").after("<font color='red'>this is replacing text</font>")
d. after : 在自己的后面添加一個兄弟
$("<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>
遍歷的操作:
<script>
var cities = ["深圳市", "東莞市", "惠州市", "廣州市"];
$(cities).each(function (i, n) {
console.log(i + "====" + n);
})
$.each(cities, function (i, n) {
console.log(i + ">>>>" + n);
})
</script>

步驟分析:
- 導入JQ的文件
- 文檔加載事件:頁面初始化
- 進一步確定事件: change事件
- 函數: 得到當前選中省份
- 得到城市, 遍歷城市數據
- 將遍歷出來的城市添加到城市的select中
代碼實現:
$(function(){
$("#province").change(function(){
// alert(this.value);
//得到城市信息
var cities = provinces[this.value];
//清空城市select中的option
/*var $city = $("#city");
//將JQ對象轉成JS對象
var citySelect = $city.get(0)
citySelect.options.length = 0;*/
$("#city").empty(); //采用JQ的方式清空
//遍歷城市數據
$(cities).each(function(i,n){
$("#city").append("<option>"+n+"</option>");
});
});
});
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Expandable "Detail" Table Rows
Expandable "Detail" Table Rows...2007-08-08
jQuery實現回車鍵(Enter)切換文本框焦點的代碼實例
這篇文章主要介紹了jQuery實現回車鍵(Enter)切換文本框焦點的代碼實例,需要的朋友可以參考下2014-05-05

