简体   繁体   English

动态生成的HTML元素后,document.getElementById返回null

[英]document.getElementById returns null after Dynamically generated HTML element

I am using prototype.js 我正在使用prototype.js

After dynamically generated Input elements when I do 在我动态生成Input元素之后

document.getElementById() or $(Id) document.getElementById()$(Id)

I get null . 我得到null UPDATE: 更新:

在此处输入图片说明

It seems to me like you did not give any id to your input field. 在我看来,您没有在输入字段中输入任何ID。 it looks like you only have name attribute. 看起来您只有name属性。 you should give it an id attribute too. 您也应该给它一个id属性。

Querying the dom for elements that are dynamicly generated doesn't make a lot of sense. 向dom查询动态生成的元素没有多大意义。

When you generated the element, save a reference to it. 生成元素时,请保存对其的引用。 That way your javascript doesn't do a lot of repetitive expensive queries. 这样,您的javascript不会执行很多重复的昂贵查询。

To answer you specific question, it should work, and you probably forgot to insert the element into the dom. 要回答您的特定问题,它应该可以工作,并且您可能忘记了将元素插入dom。

The element selected with Firebug does not have an ID attribute. 使用Firebug选择的元素没有ID属性。 Therefore, you won't be able to get it by id. 因此,您将无法通过id获取它。

As per my knowledge you are suppose to writing your JavaScript at the top of the page but the element will generate after some execution or after the execution of that java script code. 据我所知,您应该在页面顶部编写JavaScript ,但是该元素将在执行某些Java脚本代码后或在执行之后生成。

So in that case particular JavaScript code didn't got that element ID; 因此,在那种情况下,特定的JavaScript代码没有该元素ID。 so it will retrieve a null value and send error like that. 因此它将检索null值并发送类似的错误。

If possible just try to call that JavaScript at the bottom of the page OR we can say after page get load.. i think this will work for your same code.. 如果可能的话,只需尝试在页面底部调用该JavaScript ,否则我们可以说页面加载后..我认为这将对您的相同代码有效。

Just try it once, if your luck with you then will get your Element Id . 只需尝试一次,如果运气好的话,您将获得Element Id

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM