本节主要通过城市选择案例进一步讲解JavaScript。
onchange()
例1
<img id="tu" src="1.jpg" height=100>
<br>
<select name="sel" onchange="test(this)">
<option value="1.jpg" >one</option>
<option value="2.jpg">two</option>
<option value="3.jpg">three</option>
<option value="4.jpg">four</option>
</select>
<script>
var tu=document.getElementById("tu");
function test(obj){
var index=obj.selectedIndex;
tu.src=obj.options[index].value;
}
</script>
例2
demo.html
<script src="city.js"></script>
<script>
scity("pro","cit","黑龙江","大庆");
</script>
city.js
var citys=new Array(
new Array("南京","徐州","连云港"),
new Array("北京"),
new Array("天津")
);
function scity(pname,cname,xf,cs){
var province=['江苏省','北京','天津'];
document.write('<select onchange="selectc(this)" id="pro" name="+pname+">');
document.write('<option value="">--选择省份--</option>');
var a=0;
for(var i=0;i<province.length;i++){
if(typeof(xf)!="undefined"){
if(province[i]==xf)
var sel="selected";
a=i
else
var sel="";
}else{
var sel="";
}
document.write('<option '+selected+' value='''+provice[i]+'">'+provice[i]+'<option>');
}
document.write("</select>");
document.write('<select id="city" name="'+cname+'">');
document.write('<option value="">--选择城市--</option>');
document.write("</select>");
if(a>0)
selectc(document.getElementById("pro"),a,cs);
}
function selectc(pobj,a,cs){
if(typeof(a)!="undefined"){
var index=a;
}else{
var index=pobj.selectedIndex-1;
}
var index=pobj.selectedIndex-1;
var cobj=document.getElementById("city");
cobj.innerHTML="";
if(index>=0){
for(var i=0;i<citys[index].length;i++){
if(typeof(cs)!="undefined"){
if(citys[index][i]==cs)
var sel="selected";
else
var sel="";
}
var option=document.createElement("option");
var text=citys[index][i];
option.value=text;
option.selected=sel;
option.innerHTML=text;
cobj.appendChild(option);
}
}else{
var option=document.createElement("option");
option.value="";
option.innerHTML="--请选择城市--";
cobj.appendChild(option);
}
}
本文通过两个实例深入讲解JavaScript中的城市选择功能。第一个例子使用onchange事件改变图片源,第二个例子展示如何动态生成省份和城市下拉菜单,并实现选中特定城市的逻辑。涉及到的关键技术包括DOM操作和事件处理。

1626

被折叠的 条评论
为什么被折叠?



