首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

单选按钮如何不显示id 而是undefined

2013-08-24 
单选按钮怎么不显示id 而是undefined!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENh

单选按钮怎么不显示id 而是undefined

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<script>
<!--
   
    function getVById(){

var tt=this.id;
alert(tt);
}
    
-->

</script>
</head>
<body>
    <input type="radio" id="test11" name="test11" value="1"onclick="getVById()" />测试1
    <input type="radio" id="test12" name="test11" value="2" onclick="getVById()"/>测试2
   
    
</body>
<html>
HTML this?
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

直接在function里面获取的this是Window对象
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<script type="text/javascript">

   window.onload= function(){
  var atr = document.getElementsByTagName('input');
  //alert('0');
 for(i=0;i<atr.length;i++)
{

    atr[i].onclick=function (){

var tt=this.id;
alert(tt);
}
    
}

</script>
</head>
<body>
    <input type="radio" id="test11" name="test11" value="1"onclick="getVById()" />测试1
    <input type="radio" id="test12" name="test11" value="2" onclick="getVById()"/>测试2
   
    
</body>
<html>


这里我还是直接用this  但又行了  这是什么原因啊  也是直接在函数里面调用的


直接写function的意思是script标签下顶级的函数,你在那里alert一下this
然后再在atr[i].onclick=function (){...}中alert一下

参考下这篇博客和其中评论
http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

直接在function里面获取的this是Window对象
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<script type="text/javascript">

   window.onload= function(){
  var atr = document.getElementsByTagName('input');
  //alert('0');
 for(i=0;i<atr.length;i++)
{

    atr[i].onclick=function (){

var tt=this.id;
alert(tt);
}
    
}

</script>
</head>
<body>
    <input type="radio" id="test11" name="test11" value="1"onclick="getVById()" />测试1
    <input type="radio" id="test12" name="test11" value="2" onclick="getVById()"/>测试2
   
    
</body>
<html>


这里我还是直接用this  但又行了  这是什么原因啊  也是直接在函数里面调用的




你用getElementsByTagName("input")是获取的文档中所有的input对象(即是一个input元素数组),然后用for循环时就是一个input对象(或者说是一个button对象),用this的话就是指的这个button对象了。
[解决办法]
引用:
Quote: 引用:

直接在function里面获取的this是Window对象
能具体点么

1楼已经给了你答案了,你还要什么

热点排行