Greasemonkey Jquery Script to Click Links
I'm trying to do my first greasemonkey script. I'm fairly new to jquery and javascript, so be easy on me.
Here is what I have so far.
// ==UserScript==
// @name load all page comments
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
// @namespace none
// @include http://www.reddit.com/*
// ==/UserScript==
setInterval( function () {
window.alert("Hello World!");
$("a:contains('load more comments')").clic开发者_Python百科k();
}, 10000);
The goal here is to click on all of the "load more comments" page on a sample reddit page like this, and to loop doing it every ten seconds.
http://www.reddit.com/r/AskReddit/comments/i7hb5/why_assign_gender_to_public_bathrooms_if_there_is/
Right now, only the hello world alert pops up, but the links aren't clicked. So the interval function is working, but loading more comments isn't. Not sure where to go from here. Could the spaces in the 'load more comments' string be breaking it?
Any help greatly appreciated. Thanks!
See: wiki.greasespot.net/Generate_Click_Events .
That Reddit link fires JavaScript and not JS that was set with jQuery.
Which means that in this case, you need to send an actual mouse event, like so:
setInterval ( function () {
var clickEvent = document.createEvent ("HTMLEvents");
clickEvent.initEvent ("click", true, true);
$("a:contains('load more comments')")[0].dispatchEvent (clickEvent);
}, 10000);
Oops! I did not see that the question mentioned clicking "all of the 'load more comments'". (And that page has hundreds of them!)
To do that, use jQuery's each()
function...
setInterval ( function () {
var moreLinks = $("a:contains('load more comments')");
moreLinks.each ( function () {
var clickEvent = document.createEvent ("HTMLEvents");
clickEvent.initEvent ("click", true, true);
this.dispatchEvent (clickEvent);
} );
}, 10000);
You are trying to simulate click event but this only works on events attached with jQuery. Events on load more comments links at reddit attached using html attributes. I.e:
onclick="return morechildren(this, 't3_i7hb5', 'c21ko21,c21kesz,c21klil,c21ko45,c21kro5,c21l90v,c21lo38', 3, '')"
to solve your problem you need to extract values from this attributes and call them separately.
If you have jQuery loaded on the page you could just trigger the click event using jQuery
精彩评论