[英]Pulling comment scores from Reddit, greasemonkey script
我正在寻找一个润滑脂脚本,我需要从每个注释中提取分数,以便以后可以添加自己的样式。 这是我现在所拥有的:
reddit源如下所示(每个注释都会出现)
<p class="tagline">
<span class="score unvoted">16 points</span>
到目前为止,我尝试编写的JavaScript如下
var i, tags = document.querySelectorAll('.tagline');
for(i=0;i<tags.length;i++) {
var pullVotes = document.getElementsByClassName('.score'); //gets an Object HTMLCollection
var collectionPull = Array.prototype.slice.call(pullVotes); //My attempt to convert the HTMLCollection to an array
var userVote = collectionPull[0];
tags[i].innerHTML += "<span> ("+userVote+")</span>";
}
我得到“未定义”。 我也知道可以使用reddit json,但是我找不到从所有注释中提取分数的方法,仅是从我设置的静态注释中获取分数。
任何帮助,将不胜感激,谢谢!
首先,出了什么问题:
var pullVotes = document.getElementsByClassName('.score'); //gets an Object HTMLCollection
是的,它确实返回了HTMLCollection对象,但是您的行查找的是名为“ .score”的类,而不是“ score”类,因此此行返回一个空集合 。
var collectionPull = Array.prototype.slice.call(pullVotes); //My attempt to convert the HTMLCollection to an array
我不太确定您要在这里实现什么,因为HTMLCollection确实具有item(n)
方法,该方法返回...是的,该项目在索引n
(如HTMLCollection类的文档中所示)
var userVote = collectionPull[0];
好的,即使第一行起作用了,这也总是将集合的第一个元素分配给userVote
,这意味着下一行
tags[i].innerHTML += "<span> ("+userVote+")</span>";
会为页面上的所有分数分配相同的值。
可悲的是,我不知道您打算实际包含“(userVotes)”什么,因此,我认为这不能解决您的所有问题,但是我只能使用您提供的信息来做:
var i, tags = document.querySelectorAll('.tagline');
for(i=0;i<tags.length;i++) {
// get all elements with class 'score' that are inside the tagline
var userVote = tags[i].getElementsByClassName('score').item(0);
// do something with this element
userVote.style="background-color: red";
}
由于reddit的页面上有jQuery,因此您也可以简单地执行(例如)
var $ = unsafeWindow.jQuery;
$('.tagline .score').css('background-color', 'red');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.