【发布时间】:2017-08-31 15:36:33
【问题描述】:
我正在编写一个脚本以将元素附加到网页上添加的模式。
问题是我的getElementsByClassNamemethod 在运行时返回空(已编辑),但在我检查页面后返回。
$('.my-trigerring-modal-button').click(function () {
//try to avoid retrieve before modal added
setTimeout(function() {
var element = document.getElementsByClassName('Modal-form');
if(element === undefined || element.length == 0){
//always return undefined on run
return;
}
}, 5000);
})
但是当我在检查页面后在浏览器控制台中运行下面的代码时,我会检索到想要的元素
document.getElementsByClassName('Modal-form')
编辑
这是我的代码 HTML:
<button type="submit" class="my-trigerring-modal-button" style="visibility: visible;"></button>
这个 HTML 按钮存在,'Modal-form' 元素也是由我没有打开它的库脚本添加的。
对于那些问我 5 秒是否足够的人:是的! 'Modal-form' 元素显示在 5s 之前。
如果我不确定,我就不会问你这个!
我担心库脚本会阻止我的脚本覆盖他的表单,但 Chrome 在检查后有足够的权利这样做
谢谢
【问题讨论】:
-
这不可能回答?我们如何知道具有
Modal-form类的元素在哪里以及是否存在?还有getElementsByClassName一般不会返回undefined -
这可能意味着 dom 还没有加载。你可能想等待元素存在。
-
@RudraniAngira - 你认为五秒钟就够了吗?
-
请发minimal reproducible example。另外,如果你使用 jQuery,为什么不使用 jQuery?
-
@adeneo 应该够了,但根据代码,没有其他理由似乎是合理的。
标签: javascript jquery dom