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

一個對象引用問題解决方案

2012-03-20 
一個對象引用問題下面的代碼:點一次按鈕,增加一行,裏面有個input,名字為aa爲什麽無法用document.frm.aa引

一個對象引用問題
下面的代碼:點一次按鈕,增加一行,裏面有個input,名字為aa
爲什麽無法用document.frm.aa引用到這個input對象數組?怎樣才可以呢。


<script>
function   appendNewRow(){
       
        var   row=document.createElement( "TR ");  
       
          var   cell=document.createElement( "TD ");
          var   input=document.createElement( "input ");
          input.setAttribute( "type ", "text ");
        input.setAttribute( "name ", "aa ");         /////這裡設置名字為aa
        cell.appendChild(input);
        row.appendChild(cell);
        document.getElementById( "TAB ").appendChild(row);


}
function   createCellWithInput(name){
        var   cell=document.createElement( "TD ");
            var   input=document.createElement( "input ");
      input.setAttribute( "type ", "text ");
        input.setAttribute( "name ",name);
 
    cell.appendChild(input);
      return   cell;
}


</script>
<form   name=frm>
<table> <tbody     id= "TAB "> </tbody> </table>

<input   type=button   onclick= "appendNewRow();alert(document.frm.aa) ">
</form>

[解决办法]
<input type=button onclick= "appendNewRow();alert(document.frm.aa) ">
改为:
<input type=button onclick= "appendNewRow();alert(document.all.frm.aa) ">

[解决办法]
input.setAttribute( "name ", "aa ");
改成
input.setAttribute( "id ", "aa ");
就能用了
[解决办法]
<script>
function appendNewRow(){

var row=document.createElement( "TR ");
var cell=document.createElement( "TD ");
var input=document.createElement( "input ");
input.setAttribute( "type ", "text ");
input.setAttribute( "name ", "aa "); /////這裡設置名字為aa
cell.appendChild(input);
row.appendChild(cell);
document.getElementById( "TAB ").appendChild(row);
return input
}
function Alert(ctrl){
alert(ctrl.name+ ": "+ctrl.value);
}
function AllTextInputInFrm(){
var frm=document.frm;
var inputs=frm.getElementsByTagName( "INPUT ");
for(var i =0;i <inputs.length;i++){
if(inputs[i].type== 'text ' && inputs[i].name== "aa "){
alert(inputs[i].name+ ": "+inputs[i].value);
}
}
}
</script>
<form name=frm>
<table> <tbody id= "TAB "> </tbody> </table>
<input type= 'button ' onclick= "AllTextInputInFrm(); " value= "AllTextInputInFrm "/>
<input type=button onclick= "Alert(appendNewRow()); ">
</form>
------解决方案--------------------


<html>
<body>
<script>
function appendNewRow(){
var input=document.createElement( "input ");
input.setAttribute( "type ", "text ");
input.setAttribute( "name ", "aa ");
document.frm.appendChild(input);
alert(document.frm.aa);//输出undefined
alert(document.frm.bb);//输出[object]
}
</script>
<form name= "frm ">
<input type= "text " name= "bb " />
</form>
<input type= "button " onclick= "appendNewRow(); " />
</body>
</html>

实验结果,动态创建的元素无法用name属性直接引用,浏览器不识别~~

热点排行