-1

长话短说,我正在制作一个greasemonkey 脚本。我工作的页面有这个特定的表,根据页面的不同,它具有不同的值。

<table class="billing dead">
    <tbody>
        <tr>
            <th>Index:</th>
            <td>Long alpha numeric value here</td>
        </tr>
        <tr>
            <th>Status:</th>
            <td class="status">This text is red to denote urgency.</td>
        </tr>
    </tbody>
</table><!-- end billing dead -->

我需要做的是根据情况将文本“索引:”更改为其他内容,无论是按钮还是链接。我只是很难通过 Javascript 实际找到该项目。

环顾四周,我发现了这个:如何在 JavaScript 中按类获取元素?它为我提供了以下代码:

function replaceContentInContainer(matchClass,content)
{
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems)
    {
        if((" " + elems[i].className + " ").indexOf(" " + matchClass + " ") > -1)
        {
            elems[i].innerHTML = content;
        }
    }
}

这取代了整张桌子,但它是最接近我的情况的问题/答案;只是不太对劲。一旦我找到了上面链接的那个方法的表格,有没有办法访问那个特定表格的元素?我试过随意改变

elems[i].innerHTML = content;

进入

elems[i][0].innerHTML = content;

这很快告诉我这elems[i]不是节点的节点。有没有一种简单的方法来做我正在寻找的东西?

4

3 回答 3

1
document.querySelector('.billing.dead > tbody > tr > th')
        .firstChild
        .data = "new value";
于 2012-07-16T03:45:58.363 回答
0

是否有多个“计费”表?每个只有一个“索引”吗?它总是第一行吗?

以下完整的脚本显示了如何更改任何/所有“索引”行的 HTML,包括激活生成的按钮。它使用jQuery,这将为您节省大量时间和精力。

请参阅 jsFiddle 中的基本代码。

// ==UserScript==
// @name     _Buttonize the Index cells
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// ==/UserScript==

//--- Find all the "Index" headers.
var indexHdrs   = $("table.billing.dead th:contains(Index)");

//--- Wrap them all in a button, for example.
indexHdrs.each ( function () {
    $(this).wrapInner ('<button class="myButton" />');
} );

/*--- Activate the buttons.  In this case they just display matching
    cell contents.
*/
$("table.billing.dead th button.myButton").click ( function () {
    var jThis           = $(this);  //-- The button that was clicked.
    var matchingCell    = jThis.parent ().next ();
    alert (matchingCell.text () );
} );


注意:要在 Chrome 上使用此脚本,请安装Tampermonkey 扩展——无论如何,您都希望这样做,以获取额外功能,并克服 Chrome 对用户脚本安装的未决限制。

于 2012-07-16T04:34:17.727 回答
0

它运作良好。这是演示

replaceContentInContainer('status', 'hello');

于 2012-07-16T03:36:03.883 回答