1. 程式人生 > >JQuery二級聯動 ( each(callback),$.each(object, [callback]))

JQuery二級聯動 ( each(callback),$.each(object, [callback]))

1.each(callback)

HTML 程式碼:

<img/><img/>

jQuery 程式碼:

$("img").each(function(i){
   this.src = "test" + i + ".jpg";
 });

結果:

[ <img src="test0.jpg" />, <img src="test1.jpg" /> ]

 

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>使用jQuery完成省市二級聯動</title>
	

		<script type="text/javascript" src="../js/jquery-1.8.3.js"></script>
		<script>
			$(function() {
				var cities = new Array(3);
				cities[0] = new Array("武漢市", "黃岡市", "襄陽市", "荊州市");
				cities[1] = new Array("長沙市", "郴州市", "株洲市", "岳陽市");
				cities[2] = new Array("石家莊市", "邯鄲市", "廊坊市", "保定市");
				cities[3] = new Array("鄭州市", "洛陽市", "開封市", "安陽市");
				$("#province").change(function() {
					$("#city").empty();
					var val = this.value;
					$(cities).each(function(i) {
						//alert(i+":"+n);
						if (val == i) {
							$(cities[i]).each(function(j) {
								var textNode = document.createTextNode(cities[i][j]);
								var opEle = document.createElement("option");
								$(opEle).append(textNode);
								$(opEle).appendTo($("#city"));
							});
						}
					});
				});
			});
		</script>

	</head>

	<body>
		<select id="province">
			<option>--請選擇--</option>
			<option value="0">湖北</option>
			<option value="1">湖南</option>
			<option value="2">河北</option>
			<option value="3">河南</option>
		</select>
		<select id="city">
									
		</select>

	</body>

</html>

2. $.each(object, [callback])

 

 

<script>
	$(function(){
		var cities = new Array(3);
		cities[0] = new Array("武漢市","黃岡市","襄陽市","荊州市");
		cities[1] = new Array("長沙市","郴州市","株洲市","岳陽市");
		cities[2] = new Array("石家莊市","邯鄲市","廊坊市","保定市");
		cities[3] = new Array("鄭州市","洛陽市","開封市","安陽市");
		
		$("#province").change(function(){
			
			$("#city").empty();
			
			
			var val = this.value;
		
			
			$.each(cities,function(i,n){
			
				if(val==i){
					
					$.each(cities[i], function(j,m) {
						
						var textNode = document.createTextNode(m);
						
						var opEle = document.createElement("option");
						
						$(opEle).append(textNode);
						
						$(opEle).appendTo($("#city"));
					});
				}
			});
			
		});
	});
</script>