如何将waitForKeyElements() 与通配符选择器一起使用?

问题描述

我在玩 GreaseMonkey,试图检测页面上的新评论。我的 Javascript 非常生疏。我找到了这个 waitForKeyElements() 脚本,它看起来很有帮助。我看到它正在使用 jQuery,并且我已经研究了 JQuery 通配符选择器,但它不起作用。

我什至找到了 this question and answer herethis one about jQuery selector id ends with,但仍然无法让它工作。

聊天消息由带有 <div>id="chat-messages-12345randomNum" 标识。

这是我尝试过的:

// ==UserScript==
// @name    Chat listener
// @include https://chatSite.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// ==/UserScript==

console.log("hello world");

function findNewComments (jNode) {
  
    console.log("found comment " + jNode);
}

waitForKeyElements ("div[id$='chat-messages']",findNewComments);  

'hello world' 在控制台中,所以我知道至少脚本正在加载。
我在选择器中有和没有 div 的情况下都试过了,都没有奏效。

解决方法

它似乎不起作用,因为我的选择器错误。我正在寻找以 'chat-messages-' 开头的 id,但是这个选择器“div[id$='chat-messages']”是一个带有选择器的 ENDS。选择器开头使用 '^',因此一旦我将其切换为“div[id^='chat-messages']”,它就开始查找我正在寻找的 div。

另外,仅供参考,事实证明这是 waitForKeyElements() 的一种糟糕用法,因为它只是每 300 毫秒就触发一次。