【问题标题】:click is not detecting the presence of the element点击未检测到元素的存在
【发布时间】:2018-05-31 23:32:10
【问题描述】:

嗨,

我需要 javascript 来点击一个 html 元素,但它没有立即出现在 dom 中,所以我有这个代码:

document.addEventListener("DOMContentLoaded", function(event) {
  // Select the node that will be observed for mutations
  var parentOfMyList = document.body;

  // Options for the observer (which mutations to observe)
  var config = {
    attributes: true,
    childList: true,
    subtree: true
  };

  // Callback function to execute when mutations are observed
  var callback = function(mutationsList) {
    for (var mutation of mutationsList) {
      if (mutation.type == 'childList') {
        var elt = document.getElementById("topcmm-123flashchat-main-toolbar-message-type-option");
        if (elt) {
            setTimeout(document.getElementById("topcmm-123flashchat-main-toolbar-message-type-option").click, 6000);

          observer.disconnect();
        }
      }
    }
  };

  // Create an observer instance linked to the callback function
  var observer = new MutationObserver(callback);
  observer.observe(parentOfMyList, config);
});

但我收到一条错误消息,上面写着'click' called on an object that does not implement interface HTMLElement。这是为什么?当 click() 被执行时,该元素应该已经存在了(我什至给了它 6 秒的时间来赶上)。

谢谢。

【问题讨论】:

    标签: javascript mutation-observers


    【解决方案1】:

    这与变异观察者无关。该元素在那里,但您没有在其上调用click() 方法。由于您没有将方法绑定到元素,因此在 window 上调用它。

    要么传递一个在元素上调用它的匿名函数:

    setTimeout(function() {
        elt.click();
    }, 6000);
    

    或者你可以将方法绑定到元素:

    setTimeout(elt.click.bind(elt), 6000);
    

    【讨论】:

    • 感谢您的光临。你永远是我的救星!再次感谢!
    • 只是为了大便和咯咯笑。可以说我不使用变量,而是使用document.getElementById。它的语法是什么?
    • document.getElementById("topcmm-123flashchat-main-toolbar-message-type-option").click.bind(document.getElementById("topcmm-123flashchat-main-toolbar-message-type-option"))
    • 语法完全相同,只需将elt 替换为您分配给elt 的表达式即可。
    • 我之前告诉过你,现在我仍然相信,你可能会通过使用变异观察器让事情变得比实际需要的复杂得多。
    猜你喜欢
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 2012-09-08
    • 2016-08-18
    • 2010-09-14
    相关资源
    最近更新 更多