javascript - 为什么我不能使用我的用户脚本定位特定的 div

标签 javascript jquery userscripts

我正在尝试修改 http://play.google.com/music/通过 Chrome 上的 Tampermonkey 使用用户脚本,我在尝试定位页面上的特定 div 时遇到了困难 - 似乎有什么东西阻止我修改它。

您需要登录 Google 帐户(如果没有,则可能需要添加歌曲)才能查看,但该元素似乎是这样的

<div class="new-listen-now g-content three-column" style="opacity: 1;">

它的所有 child 都完全无法成为我的脚本的目标。该脚本如下所示:

// ==UserScript==
// @name           Google Play Music Tweaks
// @description:en My personal tweaks for Google Play Music
// @namespace      www.reaverxai.com
// @require       http://code.jquery.com/jquery-1.11.3.min.js
// @include       http://play.google.com/music/listen*
// @include       https://play.google.com/music/listen*
// @include       http://music.google.com/music/listen*
// @include       https://music.google.com/music/listen*
// @match         http://play.google.com/music/listen*
// @match         https://play.google.com/music/listen*
// @match         http://music.google.com/music/listen*
// @match         https://music.google.com/music/listen*
// @run-at        document-end
// ==/UserScript==

$('.nav-toolbar').attr( "class", "testclass");
$('.recommended-header').attr( "class", "testclass");

jQuery 的第一行工作正常,正如您所期望的那样,但是第二行(针对上述元素的子元素)没有执行任何操作。

最佳答案

它可能正在由脚本加载,因此完成后不会触发任何特定事件。最好的选择是创建一个间隔并检查该元素,当它位于 DOM 中时销毁该间隔...

function whenElementLoaded() {
    // whatever you want to do when the element exists
}

var intervalID = setInterval(function() {
    if ($(".new-listen-now.g-content.three-column").length) {
        clearInterval(intervalID);
        whenElementLoaded();
    }
}, 500);

当我过去不得不使用这种方法时,我从来没有 100% 满意过它,但它确实起到了作用,而且它确实会自行清理。它应该可以满足您的需要。

关于javascript - 为什么我不能使用我的用户脚本定位特定的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32502543/

相关文章:

javascript - 在 .sticky-top 元素中调用时,弹出窗口会滚动并且某些内容会隐藏

javascript - Chrome/Tampermonkey 用户脚本存储在文件系统的什么位置?

javascript - 在 <div> 悬停时,如何找到关联的 Mapbox 标记、更改其颜色并打开弹出窗口?

javascript - Gulp - 导致任务停止的错误

javascript - 在 Javascript 中将字符串转换为二维数组的有效方法

javascript - 为什么它只适用于第一个按钮?

javascript - 删除 html 自动对焦使用 javascript/jquery

javascript - jQuery 代码无法在 Google Chrome 上运行?

javascript - 如何使用用户脚本加载共享网络 worker ?

greasemonkey - 获取 2 个用户脚本以相互交互?