为什么下述代码,最后的结果多了个undefined呢?
<body>
<select id="s1">
<option value="jia">甲</option>
<option value="yi">乙</option>
<option value="bing" selected="selected">丙</option>
</select>
<br />
<input type="button" value="点我" id="s1" onclick="inf()" />
<script type="text/javascript">
function inf()
{
var d = document.getElementById('s1');
var s = document.getElementById('s1');
var x;
var y = d.options;
for(var i=0;i<y.length;i++)
{
var txt;
txt+=y[i].text;
}
alert(txt);
}
</script>
</body>
</html>
<body>
<select id="s1">
<option value="jia">甲</option>
<option value="yi">乙</option>
<option value="bing" selected="selected">丙</option>
</select>
<br />
<input type="button" value="点我" id="s1" onclick="inf()" />
<script type="text/javascript">
function inf()
{
var d = document.getElementById('s1');
var s = document.getElementById('s1');
var x;
var y = d.options;
for(var i=0;i<y.length;i++)
{
var txt;
txt+=y[i].text;
}
alert(txt);
}
</script>
</body>
</html>
{
var txt; // 是局部变量,只有在此循环类才能访问!且每次循环都是一个新的对象
txt+=y[i].text;
}
alert(txt);==》
var txt;
for(var i=0;i<y.length;i++)
{
txt+=y[i].text;
}
alert(txt);
{
var d = document.getElementById('s1');
var s = document.getElementById('s1');
var x;
var y = d.options;
var txt='';
for(var i=0;i<y.length;i++)
{
txt+=y[i].text;
}
alert(txt);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head><body>
<select id="s1">
<option value="jia">甲</option>
<option value="yi">乙</option>
<option value="bing" selected="selected">丙</option>
</select>
<br />
<input type="button" value="点我" id="s2" onclick="inf()" />
<script type="text/javascript">
function inf()
{
var d = document.getElementById('s1');
var x="";
var y=new Array()
y = d.options;
for(var i=0;i<y.length;i++)
{
var txt="";
txt+=y[i].text;
}
alert(txt);
}
</script>
</body>
</html>
如果是想输出所有的下拉列表!<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head><body>
<select id="s1">
<option value="jia">甲</option>
<option value="yi">乙</option>
<option value="bing" selected="selected">丙</option>
</select>
<br />
<input type="button" value="点我" id="s2" onclick="inf()" />
<script type="text/javascript">
function inf()
{
var d = document.getElementById('s1');
var x="";
var y=new Array();
y = document.getElementById("s1").getElementsByTagName('option');
alert(y.length);
var txt="";
for(var i=0;i<y.length;i++)
{
txt+=y[i].text;
}
alert(txt);
}
</script>
</body>
</html>
var txt=“”;
就ok;了!
主要是在第一次循环的时候txt没值!当然就是undefined
for(var i=0;i<y.length;i++)
{txt+=y[i].text;
}