[英]Difficulty setting focus on newly created object in javascript
So, related to an earlier question, but forgive me for my naive javascript ways. 因此,与先前的问题有关,但请原谅我的幼稚javascript方法。 Basically I now want to automatically bring a text input into focus when it is added to the DOM.
基本上,我现在想将文本输入添加到DOM后自动使其成为焦点。 Part of me thinks that I might be trying to add focus to the object before it exists, but I'm not quite sure how I would go about fixing it.
我的一部分认为我可能会尝试在该对象存在之前为其添加焦点,但是我不太确定如何解决该问题。 Right now this is my relevant code:
现在,这是我的相关代码:
var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";
this.parentNode.replaceChild(searchWrapper, this);
document.getElementById("search-wrapper").focus();
But it's not quite working. 但这不是很有效。 Should I be setting focus as a callback on replaceChild, or is there some other way to do this?
我应该将焦点设置为replaceChild的回调,还是有其他方法可以做到这一点?
Try the following: 请尝试以下操作:
var searchOrig = document.getElementById("search-wrapper");
var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";
searchWrapper.setAttribute('tabindex', '0');
searchOrig.parentElement.replaceChild(searchWrapper, searchOrig);
document.getElementById("search-wrapper").focus();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.