我想写一个greasemonkey脚本,我需要从每个评论中提取分数,这样我就可以添加我自己的样式化之后。下面是我现在的代码:
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>";
}
我得到"undefined"。我也知道有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";
}
jQuery 因为reddit在他们的页面上有jQuery,你也可以简单地做(例如)
var $ = unsafeWindow.jQuery;
$('.tagline .score').css('background-color', 'red');