单击未检测到元素的存在

click is not detecting the presence of the element

嗨,

我需要 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 秒的领先优势来赶上)。

谢谢。

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

上被调用

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

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

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

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