如题,我想要写一个新浪微博浏览器扩展,在新浪微博的个人主页加载脚本
在第一步就遇到了问题。我经过审查元素,直接在chrome 的控制台上输入
$('.WB_detail');
经过测试是能够出现array-like 的对象的。于是,我接下来开始在油猴脚本tampermonkey 上面写,代码简单来说就是:
// ==UserScript==
// @name 新浪微博demo
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match http://weibo.com/*
// @grant none
// @require http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js
// ==/UserScript==
(function() {
'use strict';
$(document ).ready(function() {
var detail=$('.WB_detail');
console.log(detail);
});
})();
但是这样加载脚本之后,打印出来的detail内容length是0,
[prevObject: n.fn.init(1), context: document, selector: ".WB_detail"] ,也就是说选择器并没有正确地选择出元素来。
同样的问题,当我用原生javascript测试,
window.onload=function(){
var detail=document.querySelectorAll('.WB_detail');
console.log(detail);
}
打印出来的结果,detail为null,也是没有取到值的。但是在浏览器控制台输入上面两行代码,又分明能取到值。
上面的代码应该都能够复现。以前这个问题也遇到过,这次遇到了不能忍了,还是想问问为什么,有哪些知识点是我疏忽的。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
是动态添加的元素吧, 在document 加载完成后才进行的渲染, 如果不确定可以尝试查看源代码能否找到对应元素, 解决办法可以通过 setTimeout 来延迟获取,或者 setInterval 抓取