2011-05-25 90 views
9

我試圖修改頁面的HTML標記以便使用JavaScript添加一些按鈕。使用JavaScript將按鈕添加到HTML頁面

您可以在下面找到我想要修改的頁面的「片段」(很長,我很抱歉,但我確實需要您獲取頁面的結構)。

我的JavaScript代碼是由瀏覽器擴展插入(我可以成功添加JavaScript的頁面,並使其運行),它應該做的唯一操作是添加一個按鈕到合適的位置。

該HTML頁面包含一個帶有表格的<FORM>
一些行和單元格後,有是包含3個輸入按鈕的小區:

<input type="submit" name="submit" value="Set Ships"> 
<input type="button" name="sel" value="Select all" onclick="alert('Not Allowed.');"> 
<input type="button" name="desel" value="Deselect all" onclick="alert('Not Alloowed.');"> 

我想我的JavaScript代碼只是desel按鈕後,放置第四個按鈕。 這是我使用添加按鈕的代碼:

function add() { 
    var element = document.createElement("input"); 
    element.setAttribute("type", "button"); 
    element.setAttribute("value", "invert"); 
    element.setAttribute("name", "button3"); 
    element.setAttribute("onclick", "foo()"); 
    document.flotta.appendChild(element); 
} 

此代碼顯然會將按鈕直接在我的文檔的末尾,只是形式(命名flotta)之後。

我意識到我不能使用功能getElementById,因爲在按鈕之前的<td>標記沒有關聯id

因此,我問,如果有人能指出我的解決方案,將第四個按鈕添加到正確的位置。

<html> 
    <head> 
    <title>fee foo</title> 
     . . . head code 
    </head> 

<body > 
    <div id="Layer" name="Layer" /*other attributes*/"></div> 
    <table /*table attributes*/> 
    . . . table content 
    </table> 
<form id="flotta" name="flotta" method="post" action="home.php?sel=gestioneflotta"> 
    <table /*table attributes*/> 
     <tbody> 
      <tr><td> 
      <table /* attributes*/> 
       <tbody><tr> 
       <td /* attributes*/></td> 
       <td /* attributes*/></td> 
       <td /* attributes*/></td> 
       </tr> 
       <tr> 
       <td /* attributes*/">&nbsp;</td> 
       <td bgcolor="ffffff" background="bg/pergamena.jpg" align="center"> 
       <input type="submit" name="submit" value="Set Ships"> 
       <input type="button" name="sel" value="Select all" onclick="alert('Not Allowed.');"> 
       <input type="button" name="desel" value="Deselect all" onclick="alert('Not Alloowed.');"> </td> 
       <td background="bg/menu_d.gif">&nbsp;</td> 
       </tr> 
       <tr> 
       <td /* attributes*/" width="11" height="11"></td> 
       <td /* attributes*/></td> 
       <td /* attributes*/></td> 
      </tr> 
      </tbody> 
      </table> 
     </td></tr> 
      <tr> 
      . . . another row 
      </tr> 

     </tbody> 
    </table> 
</form> 
<table border="0" cellspacing="0" cellpadding="0" align=center width=510> 
    . . . another table 
</table> 

<script type="text/javascript"> 
some script 
</script> 
</body> 

</html> 
+3

請勿使用'setAttribute'設置按鈕屬性;使用直接屬性,比如'element.type =「button」;'。 * *尤其不要使用語法來分配事件處理程序,只是使用'element.onclick = FOO;'(或標準DOM級別2功能中的一個)。 – 2011-05-25 10:50:36

+0

爲什麼不u使用jQuery的 – 2011-05-25 10:53:20

+1

@marcel謝謝你的小費,但是我的注意力更側重於如何將物品放置在正確的位置。你能幫我嗎? – nick2k3 2011-05-25 10:55:02

回答

6

下面的代碼應該獲得TD:

var td = document.getElementsByName('desel')[0].parentNode; 

基本上,它得到所有的字段/按鈕名稱爲「DESEL」,並假定只有一個有,獲得第一的父元素(應該是包含按鈕的td)。

+0

謝謝,這是它! – nick2k3 2011-05-25 11:48:10