Javascript动态文本框改变焦点

标签 javascript html dom-events onfocus

我有一个 HTML 表单,其中包含一些静态文本框和一个用于创建动态文本框的按钮。现在,当单击按钮时,我希望新创建的框成为焦点。我正在使用 focus() 方法,但它不起作用。另一件事是我有一个 onFocus() 方法可以改变背景颜色,它在静态框中有效,但在动态框中无效。

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";
}

请帮忙。我是 JS 的新手。

最佳答案

尝试:

<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>

关于Javascript动态文本框改变焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13767074/

相关文章:

javascript - 防止 window.onload 被覆盖

javascript - 如何在 Google Analytics 中对虚拟浏览量进行分类?

javascript - javascript setTimeout 执行时间需要多倍的时间可能是什么原因?

javascript - 我可以通过单击事件触发多个功能吗?

javascript - HTML5/CSS3 动画

javascript - 哪些 JavaScript 事件可以触发弹出窗口而不被阻止?

php - jQuery "load()"无法加载 PHP "curl_exec()"结果

javascript - ProtractorJS 规范未运行,浏览器获取数据;仅有的

javascript - 向 Quill 添加自定义按钮操作

html - 谷歌广告下的 AJAX 消息