【问题标题】:Javascript getElementsByClassName only after inspectJavascript getElementsByClassName 仅在检查后
【发布时间】: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


【解决方案1】:

问题可能来自元素可能尚未加载。请改用 onclick="";

<a onclick="stackOverflow()"></a>

我也单独使用了原始 javascript

function stackOverflow() {
    //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);
}

虽然我不知道你为什么使用 5000 毫秒,但它似乎很长。

【讨论】:

    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2015-04-07
    • 1970-01-01
    • 2013-07-18
    • 2015-11-10
    • 2013-03-20
    相关资源
    最近更新 更多