使用greasemonkey在表之前添加HTML [英] Use greasemonkey to add HTML before table

查看:89
本文介绍了使用greasemonkey在表之前添加HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用greasemonkey来编辑页面。我需要在页面上已有的两个表之间添加自己的表,然后删除第二个表。没有什么真正设置两个现有的表分开,所以我遇到了函数 insertBefore 的问题。

I am using greasemonkey to edit a page. I need to add my own table between the two tables that are already on the page and then remove the second table. There is nothing really setting the two existing tables apart, so I am having trouble with the function to insertBefore.

<h3>Table 1</h3>
<table class="details" border="1" cellpadding="0" cellspacing="0">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr> 
</tbody></table>

<h3>Table 2</h3>
<table class="details" border="1">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr><tr>
<th>3</th>
<td>4</td>
</tr> 
</tbody></table>

我发现以下代码有助于删除表2,但我需要先添加自己的表表2首先:

I have found the below code helpful in removing table 2, but I need to add my own table before table 2 first:

// find second <table> on this page 
var xpathResult = document.evaluate('(//table[@class="details"])[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node=xpathResult.singleNodeValue;

// now hide it :)
node.style.display='none'; 


推荐答案

这是介绍jQuery的好机会。 jQuery将对你的GM脚本所做的其他事情有用,此外,它具有强大的跨浏览功能(用于重用你的代码)。

This is a good chance to introduce jQuery. jQuery will be dead useful for the other things your GM script will do, plus, it's robust and cross-browser capable (for reusing your code).

(1)添加这行到Greasemonkey元数据部分,在 // @include 指令之后:

(1) Add this line to the Greasemonkey metadata section, after the // @include directive(s):

// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

(注意,您可能必须卸载然后重新安装脚本才能复制jQuery。)

(Note you may have to uninstall and then reinstall the script to get jQuery copied over.)

(2)然后您可以使用此代码添加您的表并删除旧表:

(2) Then you can use this code to add your table and delete the old one:

//--- Get the 2nd table with class "details".
var jSecondTable    = $("table.details:eq(1)");

//--- Insert my table before it.
jSecondTable.before 
(
    '<table id="myTable">'
  + '    <tr>'
  + '        <th></th>'
  + '        <th></th>'
  + '    </tr>'
  + '    <tr>'
  + '        <td></td>'
  + '        <td></td>'
  + '    </tr>'
  + '</table>'
);

//--- Delete the undesired table.
jSecondTable.remove ();

/*--- Alternately, just hide the undesired table.
jSecondTable.hide ();
*/



您可以看到此代码的版本,在行动中,在 jsFiddle




You can see a version of this code, in action, at jsFiddle.

添加表格的替代方法 - 不那么直截了当但不要求所有报价:

Alternate method of adding your table -- Less straightforward but does not require all the quotes:

jSecondTable.before ( (<><![CDATA[
    <table id="myTable">
        <tr>
            <th></th>
            <th></th>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
    ]]></>).toString ()
);

这篇关于使用greasemonkey在表之前添加HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆