开发者

Writing my First Grease Monkey Script. How do I get innerHTML to use 'contains'?

开发者 https://www.devze.com 2023-03-14 19:59 出处:网络
I\'m basing it on another script as, although I\'m somewhat familiar with javascript, I\'m still learning.

I'm basing it on another script as, although I'm somewhat familiar with javascript, I'm still learning.

// ==UserScript==
// @name           click all "load more" prompts
// @namespace      none
// @include        http://www.reddit.com/*
// ==/UserScript==

setTimeout('var deleted = 0;var links = document开发者_如何学C.getElementsByTagName("a");var i = 0;var d = 0;for (i = 0; i < links.length; i++) {var l = links[i];if (l.href) {if (l.innerHTML == "load more comments") {toggle(l);   d = 1;  } } } , 4000);

Now, the problem seems to be that none of the innerHTM just says "load more comments."

Instead, it says something like, "load more comments (x replies)" where x can be any number.

Is there a simple way to check and see if the innerHTML contains the term "load more comments" rather than checking for exact equivalence?

Here is a page with the "load more comments" links I'm referring to: http://www.reddit.com/r/AskReddit/comments/g4c8a/whats_the_funniest_thing_you_have_heard_that_you/

Edit:

Here is the updated script. Doesn't seem to run though, any advice?

links = document.getElementsByTagName("a");
var i = 0;
for (i = 0; i < links.length; i++){
    var l = links[i];
    if (l.href){
        if (l.innerHTML.indexOf("load more comments") > -1) {
            toggle(l);
        }
    }
}


Since this is JavaScript and innerHTML is a string you can just use a JS string method for this. The traditional way is indexOf

if(l.innerHTML.indexOf("load more comments") > -1){
   // substring found
}

Less traditionally you can use regular expression, or other methods.

I recommend perusing Mozilla's String documentation for details.

EDIT: That looks fine. However, I also recommend that you don't do what you're doing the way you're doing it. Doing anything in JavaScript without using a JS library such as jQuery is ridiculously painful, even if it's something simple.

setTimeout(function(){
    $('a').each(function(i){
        if(this.href && this.innerHTML.indexOf('load more comments') > -1){
            toggle(this);
        }
    });
}, 4000);

Learn jQuery, you'll thank yourself later.

0

精彩评论

暂无评论...
验证码 换一张
取 消