elementById为null

问题描述 投票:0回答:1

在一个函数中,将创建一个HTML输入元素。调用该函数后,该元素将显示在该位置上,我可以键入该元素,但无法通过我的脚本访问它。

经过研究,我添加了一个检查元素是否确实存在,如果仍然存在,我仍然无法在脚本中更改其值...我可以在控制台中使用document.getElementById(“ txtSearchBelow”)。value ='access me'

更改值
<div id = "searchResults"></div>

document.getElementById("searchResults").innerHTML = '<input id="txtSearchBelow"class="form-control" type="text" placeholder="Search..">'+'<br>';
var inputBelow = document.getElementById("txtSearchBelow");
console.log(inputBelow);
console.log('until here it seems fine.');
var element = document.getElementById("txtSearchBelow");
 //If it isn't "undefined" and it isn't "null", then it exists.
if(typeof(element) != 'undefined' && element != null){
    alert('Element exists!');
// this here doesnt work. why not?
    document.getElementById("txtSearchBelow").value = 'eyyy please access me'; 
} else{
    alert('Element does not exist!');
}

我怎么可以通过控制台而不是在脚本中更改值?

javascript html dom
1个回答
0
投票

我会说这是因为创建元素所需的渲染时间比其后的逻辑要长。

意味着您的var元素= document.getElementById(“ txtSearchBelow”);在浏览器知道该元素之前正在执行。

在调用document.getElementById(“ txtSearchBelow”)之前放入延迟计时器

© www.soinside.com 2019 - 2024. All rights reserved.