2012-12-07 138 views
3

我有一个HTML表单,带有一些静态文本框和一个将创建动态文本框的按钮。现在,当按钮被点击时,我希望新创建的框被聚焦。我正在使用focus()方法,但它不起作用。另一件事是我会改变它在静态盒的工作背景颜色,但不是在动态框javascript动态文本框更改焦点

function addPhone(){ 
try{ 
    var phone = document.getElementById("phone"); 
    phone.appendChild(document.createElement("Phone"+noOfPhones)); 

    var textbox = document.createElement("input"); 
    textbox.setAttribute("type", "textbox"); 
    textbox.setAttribute("id","phone"+noOfPhones); 
    textbox.setAttribute("name","phone"+noOfPhones); 

    textbox.setAttributte('onFocus','onFocus(this);'); 
    textbox.style.background="lightgrey"; 

    document.getElementById("phone").appendChild(textbox); 
    phone.appendChild(document.createElement("br")); 

    textbox.focus(); 

    noOfPhones++; 
}catch(err){ 
    alert(err); 
} 

} 

function onFocus(element){ 
element.style.background = "lightgrey"; 
} 

请帮助的onfocus()方法。我是JS新手。由于

+0

呸,那是什么'尝试catch'呢?我希望这不会留在你的代码中。 –

+0

@JuanMendes绝对不会。我对JS很陌生,所以试图捕捉错误。 –

+0

您的错误将显示在控制台中,不需要try catch –

回答

1

尝试:

<div id="phone"></div> 
<input type="button" onclick="addPhone()" value="Add"/> 
<script type="text/javascript"> 
var noOfPhones=0; 
function addPhone(){ 
    try{ 
     noOfPhones++; 
     var phone = document.getElementById("phone"); 
     phone.appendChild(document.createTextNode("Phone :"+noOfPhones)); 
     var textbox = document.createElement("input"); 
     textbox.setAttribute("type", "textbox"); 
     textbox.setAttribute("id","phone"+noOfPhones); 
     textbox.setAttribute("name","phone"+noOfPhones); 
     textbox.setAttribute('onfocus','onFocus(this, true);'); 
     textbox.setAttribute('onblur','onFocus(this, false);'); 
     textbox.style.background="white"; 
     document.getElementById("phone").appendChild(textbox); 
     phone.appendChild(document.createElement("br")); 
     textbox.focus(); 
    }catch(err){ 
     alert(err); 
    } 
} 

function onFocus(element, hasFocus){ 
if(hasFocus) 
    element.style.background = "lightgrey"; 
else 
    element.style.background = "white"; 
} 
</script> 
+0

它不起作用。新的文本框没有光标。 –

+0

我用非常不寻常的方式解决了它。如果我把函数addPhone()放在html文件中,但是如果我将它移动到外部main.js文件中,它不起作用。有什么建议么? –

+0

我不知道为什么发生这种情况,但我的代码在firefox中正常工作(使用外部文件中的所有脚本)。所以我清除了Chrome中的缓存,现在它也在Chrome中工作。 –