javascript - 无法聚焦使用 JS 创建的输入
问题描述
我开始说我是新手,我的问题是我无法聚焦在纯 Js 中创建的输入字段,我只能右键单击或使用 Tab 聚焦它。
谁能解释我这里的问题在哪里,我怎么能用简单的纯JS来解决它?
如您所见,我只是在我的 DOM 中添加了一些元素。
HTML:
<script src="nuovaVoce.js"></script>
<div id="cla" onclick="nuovavoce()">+ nuova voce</div>
JAVASCRIPT:
function nuovavoce() {
var div = document.createElement('div');
var caselle = document.createElement("form");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
document.getElementById("cla").appendChild(div);
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "0px";
div.style.width = "100%";
div.style.height = "100%";
div.style.top = "0px";
div.appendChild(caselle);
caselle.setAttribute("method", "post");
caselle.setAttribute("enctype", "multipart/form-data");
caselle.setAttribute("onsubmit", "");
caselle.appendChild(input1);
input1.style.position = "static";
input1.style.width = "80%";
input1.style.height = "";
input1.style.marginLeft = "";
input1.style.marginTop = "";
input1.setAttribute("name", "titolo");
input1.setAttribute("type", "text");
caselle.appendChild(input2);
input2.style.position = "static";
input2.style.width = "80%";
input2.style.height = "";
input2.style.marginLeft = "";
input2.style.marginTop = "";
input2.setAttribute("type", "submit");
input2.setAttribute("name", "submit_categoria");
}
解决方案
我建议使用.focus()方法。在您的功能结束时,您需要添加:
add input1.focus();
function nuovavoce() {
var div = document.createElement('div');
var caselle = document.createElement("form");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
document.getElementById("cla").appendChild(div);
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "0px";
div.style.width = "100%";
div.style.height = "100%";
div.style.top = "0px";
div.appendChild(caselle);
caselle.setAttribute("method", "post");
caselle.setAttribute("enctype", "multipart/form-data");
caselle.setAttribute("onsubmit", "");
caselle.appendChild(input1);
input1.style.position = "static";
input1.style.width = "80%";
input1.style.height = "";
input1.style.marginLeft = "";
input1.style.marginTop = "";
input1.setAttribute("name", "titolo");
input1.setAttribute("type", "text");
caselle.appendChild(input2);
input2.style.position = "static";
input2.style.width = "80%";
input2.style.height = "";
input2.style.marginLeft = "";
input2.style.marginTop = "";
input2.setAttribute("type", "submit");
input2.setAttribute("name", "submit_categoria");
input1.focus();
}
<div id="cla" onclick="nuovavoce()">+ nuova voce</div>
推荐阅读
- c# - 根据 List 的属性区分
在一个班级里面 - c - C 捕获 strcat 缓冲区溢出
- intellij-idea - 隐藏 IntelliJ 2020 代码编辑器中浮动的“1 使用”指示器
- python - 从字符串更改 int 和 string
- puppeteer - 特定的 xpath 在 puppeteer js 中不起作用
- node.js - 错误:发送后无法设置标头 - Ajax、Node、Express
- vim - 更改设置后忽略突出显示
- javascript - 相邻的 JSX 元素必须包裹在封闭标记中,当它包裹在闭合标记中时
- javascript - 使用 httpClient 方法按城市名称调用 JSON 数据文件
- python-3.x - 来自路由器的配置显示为一条线路需要多线路用于 ciscoconfparse