我正在尝试修改 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/