Chrome中Tampermonkey脚本无法触发IMDb家长指南链接点击的问题
问题分析
- waitForKeyElements的选择器语法错误,多了一个闭合括号
- 回调函数传递错误,直接执行了
clickWhen()而非传入函数引用 - 目标元素的文本不在a标签内容里,而是在
aria-label属性中,原选择器无法匹配到元素 - 页面家长指南区块是动态加载的,需要准确匹配加载完成后的元素
修复后的脚本
// ==UserScript== // @name Auto Open IMDb Parents Guide // @namespace http://tampermonkey.net/ // @version 0.1 // @description Automatically navigate to Parents Guide on IMDb title pages // @author You // @match https://www.imdb.com/title/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // @run-at document-idle // ==/UserScript== (function() { waitForKeyElements( 'a[aria-label*="Parents guide"]', clickParentsGuideLink ); })(); function clickParentsGuideLink(jNode) { // 直接使用匹配到的元素跳转 window.location.href = jNode[0].href; }
关键修复点
- 修正选择器:使用
a[aria-label*="Parents guide"]匹配包含指定aria-label的a标签,不再依赖元素文本内容 - 回调函数传递:将
clickWhen()改为clickParentsGuideLink,传递函数引用而非立即执行 - 利用waitForKeyElements的参数:waitForKeyElements会把匹配到的元素作为参数传给回调函数,直接使用该参数即可,无需再次查询DOM
测试页面:https://www.imdb.com/title/tt1431045/
内容的提问来源于stack exchange,提问作者Steve Coleman
相关产品推荐
相关产品推荐

