0

我有带有 4 个提交按钮的导航表单。

<form action="index.php?do=move" method="post">
<center>
<input name="north" type="submit" value="North" /><br />
<input name="west" type="submit" value="West" /><input name="east" type="submit" value="East" /><br />
<input name="south" type="submit" value="South" />
</center>
</form>

我需要制作 js 函数,当我按下键盘上的箭头时应该提交数据。这是我的解决方案,但 ut 不起作用:)

function read_key(event){
var form  = document.createElement('form');
    form.name = "arrows";
    form.method = "POST";
    form.action = "index.php?do=move";
    var sub = document.createElement('input');
    sub.type = "submit";
    if(event.keyCode==37){
        sub.name  = "west";}
    if(event.keyCode==38){
        sub.name  = "north";}
    if(event.keyCode==39){
        sub.name  = "east";}
    if(event.keyCode==40){
        sub.name  = "south";}   
    form.appendChild(sub);
    document.arrows.submit();
}

并通过 body onkeypress = "read_key(event)" 将其连接到 html。有人可以帮我找出错误在哪里吗?我想在没有像 jQuery 这样的扩展库的情况下使用它。对不起,我的英语不好。

4

1 回答 1

0

您必须将表单附加到 DOM。这应该有效:

function read_key(event){
    if(event.keyCode >=37 && event.keyCode <=40) {
    var form  = document.createElement('form');
        form.name = "arrows";
        form.method = "POST";
        form.action = "index.php?do=move";
        var sub = document.createElement('input');
        sub.type = "submit";
        if(event.keyCode==37){
            sub.name  = "west";}
        if(event.keyCode==38){
            sub.name  = "north";}
        if(event.keyCode==39){
            sub.name  = "east";}
        if(event.keyCode==40){
            sub.name  = "south";}   
        form.appendChild(sub);
        // you have to append the form to body
        document.body.appendChild(form);
        // you can do it like that:
        // document.arrows.submit();
        // but simpler is:
        form.submit();
        // remove it after submit
        document.body.removeChild(form);
    }
}
于 2013-02-02T21:18:15.820 回答