2011-01-08 64 views
1

之前添加HTML我正在使用greasemonkey編輯頁面。我需要在已經在頁面上的兩個表之間添加我自己的表格,然後刪除第二個表格。沒有什麼可以將兩個現有表格分開設置,所以我在insertBefore的功能上遇到問題。使用greasemonkey在表

<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前未添加自己的表:

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

這是介紹jQuery的一個很好的機會。 jQuery對於你的GM腳本將做的其他事情將不再有用,此外,它強大且跨瀏覽器能力(用於重用你的代碼)。

(1)添加此行到Greasemonkey的元數據段,// @include指令(S)後:

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

(請注意您可能必須卸載,然後重新安裝腳本得到jQuery的複製)

(2)然後,您可以使用此代碼添加到您的表並刪除舊的:

//--- 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處看到此代碼的一個版本。

加入你的表

替代方法 - 那麼直接,但不要求所有的報價:

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

那輝煌。第二種方法使其非常容易。非常感謝! – 2011-01-09 16:21:52