JavaScript发送帖子没有扩展库

时间:2013-02-02 21:04:20

标签: javascript forms post submit

我有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这样的扩展库的情况下重新使用它。抱歉我的英语不好。

1 个答案:

答案 0 :(得分: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);
    }
}