2011-05-25 86 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