使用Javascript在HTML页面上添加按钮

9
我正在尝试使用JavaScript修改页面的HTML标记,以便添加一些按钮。
下面是我正在尝试修改的页面的“片段”(相当长,我很抱歉,但我真的需要您了解页面的结构)。
我的JavaScript代码由浏览器扩展插入(我可以成功地将JavaScript添加到页面并运行它),它唯一的操作是在正确的位置添加一个按钮。
HTML页面包含一个带有表格的
。在一些行和单元格之后,有一个包含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 level 2函数)。 - Marcel Korpel
1
@marcel谢谢你的建议,但是我的注意力更集中在如何将物品放置在正确的位置上。你能帮忙吗? - nick2k3
1个回答

6
以下代码应该获取td:
var td = document.getElementsByName('desel')[0].parentNode;

基本上,它获取所有名称为“desel”的字段/按钮,并假设只有一个,获取第一个元素的父级(应该是包含按钮的td)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接