有jquery的情况下创建元素后如何执行javascript代码

有jquery的情况下创建元素后如何执行javascript代码

本文介绍了在没有jquery的情况下创建元素后如何执行javascript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 chrome 扩展程序,它可以修改网站中的元素.该网站在加载主文档后发送大量 ajax 调用以获取页面内容(GWT 框架架构).我需要修改那个网页的内容,我要修改的元素只有在所有ajax调用之后才会被创建.

I am developing a chrome extension which would modify an element in a website. That website sends a lot of ajax call after loading the main document to get page contents (GWT framework architecture). I need to modify the content of that webpage and the element that I want to modify will be created only after all the ajax calls.

假设我要修改的元素的 id 是 #idContainer >div >div.container.container\--wider.\\30,只有在ajax调用完成后才可用.

let's assume that the id of element that i want to modify is #idContainer > div > div.container.container\--wider.\\30, which will be available only after the completion of the ajax call.

那么如何在此元素可用后执行 js 代码(通过 chrome 扩展 -> 内容脚本).

so how to execute a js code (via chrome extension -> content script) after this element is available.

注意:我在 stackOverflow 中看到过很多类似的问题,但没有一个不使用 jQuery 就能得到答案.

Note:I have seen many similar questions in stackOverflow but none of them have answers without using jQuery.

推荐答案

考虑使用 突变观察者.这是我必须解决完全相同问题的一些项目的示例.

Consider using a Mutation Observer. Here is an example of some of my projects where I had to solve the exact same problem.

// observer callback
const callback = (mutations) => {
  const matching = [];
  for (const {addedNodes} of mutations) { // for each mutation
    for (const node of addedNodes) { // iterate through all added nodes
      if (node.nodeType !== Node.ELEMENT_NODE) {
        continue; // only react to real element nodes
      }
      if (node.children[0]) { // Here you can check for what you want
        matching.push(...node.getElementsByTagName('pre'));
      }
    }
  }
  if (matching.length === 2) { // I needed the second pre tag
    ipcRenderer.send('note-result', matching[1].innerText);
  }
};

// intialize the observer with the callback
const observer = new MutationObserver(callback);
// pass a targetNode and an options object in the observe method
observer.observe(document.body, {attributes: true, childList: true, subtree: true});

在这个例子中,我对出现在 DOM 中的第二个pre"标签的 textContent 感兴趣.

您也可以使用断开连接方法停止观察:

You can also stop observing with the disconnect method:

observer.disconnect();

您必须根据您的特定用例稍微调整代码,但这是使用变异观察器的要点.

You have to adjust the code somewhat to your particular use case but this is the gist of using a mutation observer.

这篇关于在没有jquery的情况下创建元素后如何执行javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:58