Use greasemonkey to add HTML before table

元气小坏坏 提交于 2019-12-02 13:30:26

问题


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>

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'; 

回答1:


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) 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

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

(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 ();
*/


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 ()
);


来源:https://stackoverflow.com/questions/4636856/use-greasemonkey-to-add-html-before-table

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