Greasemonkey script to find rows with certain conditions

落花浮王杯 提交于 2019-12-10 21:53:25

问题


I tried some different ways do find rows in a table where a columns contain a particular link.

My goal: replace an icon when a link to xyz is in this same row as the image.

This is my snippet so far:

var rows = document.getElementsByTagName("tr");
for(var i = rows.length - 1; i >= 0; i--) {     
        var links = rows[i].getElementsByTagName("a");
        for(var k = links.length - k; k >= 0; k--) {
            if (links[k].href =="http://www.XXXX.net/forum/index.php?showforum=121"){
                var images = rows[i].getElementsByTagName("img");
                    for (var j=0;j<images.length;j++) {
                    images[j].src = "http://www.XXXX.net/forum/folder_post_icons/icon7.gif";
                    }
            }
        }
}

I'm pretty sure this is not really the best concept. But as you might see I try to search links in all rows and once the link to forum "121" is found, I try to replace all images in this particular row.

What I get is every image at the site getting replaced.


回答1:


Since it's simple enough, here's a complete script that does that.
It uses jQuery and here's a handy jQuery reference. See, especially, the Selectors section (which are almost the same as CSS Selectors).

Re: "What I get is every image at the site getting replaced." ...

This maybe because the search criteria is too broad. If it's a poorly designed (uses table layouts) page, every image may be in a table row with a target link!

When posting Greasemonkey questions, link to the target page, or at the very minimum, post enough of the page's HTML that we can adjust the GM script to match.


Anyway, this will work, possibly pending more information about the target page:

// ==UserScript==
// @name     _Replace image on custom-targeted row
// @include  http://www.XXXX.net/forum/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

//--- This may need tuning based on information not provided!
var targetLinks = $("tr a[href*='showforum=121']");

//--- Loop through the links and rewrite images that are in the same row.
targetLinks.each ( function () {
    //--- This next assumes that the link is a direct child of tr > td.
    var thisRow = $(this).parent ().parent ();

    //--- This may need tuning based on information not provided!
    var images  = thisRow.find ("td img");

    //--- Replace all target images in the current row.
    images.each ( function () {
        $(this).attr (  
            'src', 
            'http://www.XXXX.net/forum/folder_post_icons/icon7.gif'
        );
    } );
} );


来源:https://stackoverflow.com/questions/8098115/greasemonkey-script-to-find-rows-with-certain-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!