tansuo 发表于 2023-11-9 13:45:53

调用函数无法立即执行

在myFunction()中调用monitorDomChange()没法立即执行到该函数体中,而是for完之后再执行到该函数体中,请问如何解决
function myFunction() {
$(document).ready(function(){
// 获取指定 ID 的元素
const parentElement = document.getElementById('treeDemo');
// 获取所有子元素
const childElements = parentElement.children;
// 遍历所有子元素
for (let i = 0; i < childElements.length; i++) {
// 判断当前元素是否为 li 标签
if (childElements.tagName === 'LI') {
    // 获取 li 标签的 ID 并赋值给 document.getElementById()
    const id = childElements.id;
    // 在这里可以执行你需要的操作,例如打印 ID 或其他操作
    console.log(`Element with ID ${id+"_span"} found.`);
    const targetElement = document.getElementById(id + "_span"); // Correct the way to concatenate the string.
    console.log(targetElement);
    // 模拟点击事件
    if (targetElement) {
      const event = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
      view: unsafeWindow,
      interval: 5000 // Use the interval parameter here.
      });
debugger
      setTimeout(() => {
    monitorDomChange();
}, 0);
      targetElement.dispatchEvent(event);
    } else {
      console.log('目标 ul 元素不存在!');
    }
}
}
});
}
function monitorDomChange() {
// 你的代码在这里,例如:
}

李恒道 发表于 2023-11-9 13:45:54

[油猴脚本开发指南]包装异步代码为同步代码
https://bbs.tampermonkey.net.cn/thread-883-1-1.html

宏任务与微任务的问题
可以将setinterval包裹成promise然后await

tansuo 发表于 2023-11-9 18:57:36

李恒道 发表于 2023-11-9 18:04
[油猴脚本开发指南]包装异步代码为同步代码
https://bbs.tampermonkey.net.cn/thread-883-1-1.html



这样写吗?大佬
function myFunction() {
$(document).ready(function() {
    // 获取指定 ID 的元素
    const parentElement = document.getElementById('treeDemo');
    // 获取所有子元素
    const childElements = parentElement.children;
    // 遍历所有子元素
    for (let i = 0; i < childElements.length; i++) {
      // 判断当前元素是否为 li 标签
      if (childElements.tagName === 'LI') {
      // 获取 li 标签的 ID 并赋值给 document.getElementById()
      const id = childElements.id;
      // 在这里可以执行你需要的操作,例如打印 ID 或其他操作
      console.log(`Element with ID ${id+"_span"} found.`);
      const targetElement = document.getElementById(id + "_span"); // Correct the way to concatenate the string.
      console.log(targetElement);
      // 模拟点击事件
      if (targetElement) {
          const event = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: unsafeWindow,
          });
          targetElement.dispatchEvent(event);

          let p=new Promise((resolve, reject) => {
            setTimeout(() => {
                  debugger
               monitorDomChange();
               }, 0);
            });
      } else {
          console.log('目标 ul 元素不存在!');
      }
      }
    }
});
}

李恒道 发表于 2023-11-9 19:05:42

tansuo 发表于 2023-11-9 18:57
这样写吗?大佬
function myFunction() {
$(document).ready(function() {


我盲猜哥哥又没看帖子...
我用的async+await,哥哥只用了一个promise,一点同步的语法糖都没用上

李恒道 发表于 2023-11-9 19:07:08

```js
async function myFunction() {
$(document).ready(function() {
    // 获取指定 ID 的元素
    const parentElement = document.getElementById('treeDemo');
    // 获取所有子元素
    const childElements = parentElement.children;
    // 遍历所有子元素
    for (let i = 0; i < childElements.length; i++) {
      // 判断当前元素是否为 li 标签
      if (childElements.tagName === 'LI') {
      // 获取 li 标签的 ID 并赋值给 document.getElementById()
      const id = childElements.id;
      // 在这里可以执行你需要的操作,例如打印 ID 或其他操作
      console.log(`Element with ID ${id+"_span"} found.`);
      const targetElement = document.getElementById(id + "_span"); // Correct the way to concatenate the string.
      console.log(targetElement);
      // 模拟点击事件
      if (targetElement) {
          const event = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: unsafeWindow,
          });
          targetElement.dispatchEvent(event);

          await new Promise((resolve, reject) => {
            setTimeout(() => {
                  debugger
               monitorDomChange();
               }, 0);
            });
      } else {
          console.log('目标 ul 元素不存在!');
      }
      }
    }
});
}
```

这样随便看几行丢一下gpt,没耐心慢慢磨语法很难有提升的

tansuo 发表于 2023-11-9 19:46:11

李恒道 发表于 2023-11-9 19:07
```js
async function myFunction() {
$(document).ready(function() {


报这个错误 unexpected tokennew

李恒道 发表于 2023-11-9 19:53:03

```js
function myFunction() {
$(document).ready(async function() {
    // 获取指定 ID 的元素
    const parentElement = document.getElementById('treeDemo');
    // 获取所有子元素
    const childElements = parentElement.children;
    // 遍历所有子元素
    for (let i = 0; i < childElements.length; i++) {
      // 判断当前元素是否为 li 标签
      if (childElements.tagName === 'LI') {
      // 获取 li 标签的 ID 并赋值给 document.getElementById()
      const id = childElements.id;
      // 在这里可以执行你需要的操作,例如打印 ID 或其他操作
      console.log(`Element with ID ${id+"_span"} found.`);
      const targetElement = document.getElementById(id + "_span"); // Correct the way to concatenate the string.
      console.log(targetElement);
      // 模拟点击事件
      if (targetElement) {
          const event = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: unsafeWindow,
          });
          targetElement.dispatchEvent(event);

          await new Promise((resolve, reject) => {
            setTimeout(() => {
                  debugger
               monitorDomChange();
               }, 0);
            });
      } else {
          console.log('目标 ul 元素不存在!');
      }
      }
    }
});
}
```

tansuo 发表于 2023-11-10 07:53:45

李恒道 发表于 2023-11-9 19:53
```js
function myFunction() {
$(document).ready(async function() {


大佬,注释掉你的代码能进去,用你的代码就跑到console.log(1111);,不知道什么原因
// ==UserScript==
// @name         zh
// @match      https://*
// @grant      GM_registerMenuCommand
// @grant      GM_getValue
// @grant      GM_setValue
// @grant      unsafeWindow
// @run-at       document-start
// ==/UserScript==
var _GM_registerMenuCommand = /* @__PURE__ */ (() => typeof GM_registerMenuCommand != "undefined" ? GM_registerMenuCommand : void 0)();
// 使用GM_registerMenuCommand注册一个新的菜单项
_GM_registerMenuCommand("Start Scraping", startScraping);
function startScraping() {
// 调用你的函数,设置变量为true
myFunction()
}
function myFunction() {
    console.log(1111);
//$(document).ready(async function(){
   $(document).ready( function(){
      console.log(2222);
    // 获取指定 ID 的元素
    const parentElement = document.getElementById('treeDemo');
    // 获取所有子元素
    const childElements = parentElement.children;
    // 遍历所有子元素
    for (let i = 0; i < childElements.length; i++) {
      // 判断当前元素是否为 li 标签
      if (childElements.tagName === 'LI') {
      // 获取 li 标签的 ID 并赋值给 document.getElementById()
      const id = childElements.id;
      // 在这里可以执行你需要的操作,例如打印 ID 或其他操作
      console.log(`Element with ID ${id+"_span"} found.`);
      const targetElement = document.getElementById(id + "_span"); // Correct the way to concatenate the string.
      console.log(targetElement);
      // 模拟点击事件
      if (targetElement) {
          const event = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: unsafeWindow,
          });
          targetElement.dispatchEvent(event);

         // await new Promise((resolve, reject) => {
             // setTimeout(() => {
                  //debugger
               monitorDomChange();
                // }, 0);
             // });
      } else {
          console.log('目标 ul 元素不存在!');
      }
      }
    }
});
}
function monitorDomChange() {
// 你的代码在这里,例如:
const observer = new MutationObserver(function(mutations) {
// 其它代码
      });
observer.observe(document.body, { childList: true, subtree: true, attributes: true });
}

李恒道 发表于 2023-11-10 08:07:52

tansuo 发表于 2023-11-10 07:53
大佬,注释掉你的代码能进去,用你的代码就跑到console.log(1111);,不知道什么原因
// ==UserScript==
/ ...

你应该还有其他代码需要同步,async具有传染性的
这个要哥哥自己理解同步与异步问题了...

tansuo 发表于 2023-11-10 09:01:27

李恒道 发表于 2023-11-10 08:07
你应该还有其他代码需要同步,async具有传染性的
这个要哥哥自己理解同步与异步问题了... ...

monitorDomChange()除了这个代码其它代码都是全的,应该没有
页: [1] 2
查看完整版本: 调用函数无法立即执行