2012-07-08 101 views
0

请考虑以下非工作HTML文档:表单提交去使用Javascript - 并保持在同一页

<html> 
    <body> 
     <form action="" method="GET" onsubmit="return f(this);"> 
      <input type="text" name="bar" value="" /> 
      <input type="button" name="foo" value="foo" /> 
     </form> 
    </body> 
    <script type="text/javascript"> 
     function f(x) { 
      alert(x.bar); 
     } 
    </script> 
</html> 

我想实现的是,当是(a)foo的按钮被按下;或(b)在文本输入具有焦点时按下Enter键;那么函数f就会被调用,并带有s文本输入的内容 - 而浏览器应该在f返回后保持在同一页面上。

我该如何做到这一点?

+0

什么不适用于该文件? – Bergi 2012-07-08 20:19:20

回答

3

你应该使用一个提交输入,而不是一个按钮输入,并获得从文本输入您使用的价值属性中的文本,并返回false,以防止形式从提交

<html> 
    <body> 
     <form action="" method="GET" onsubmit="return f(this);"> 
      <input type="text" name="bar" value="" /> 
      <input type="submit" name="foo" value="foo"/> 
     </form> 
     <script type="text/javascript"> 
       function f(x) 
       { 
        alert(x.bar.value); 
        return false; 
       } 
     </script> 
     </body> 
</html> 

FIDDLE

0

只需用值而不是表单元素调用它?

onsubmit="return f(this.bar.value);" 

为了防止页面的发送,你可以从f返回false

但是使用适当的事件处理程序而不是onsubmit-attribute会更简洁。阅读更多关于他们here

<html> 
    <body> 
     <form id="inputform" action="" method="GET"> 
      <input type="text" name="bar" value="" /> 
      <input type="button" name="foo" value="foo"/> 
     </form> 
     <script type="text/javascript"> 
     function f(x) { 
      alert(x.bar); 
     } 
     var form = document.getElementById("inputform"); 
     form.onsubmit = function(event) { 
      var x = f(form.bar.value); 
      if (!x) 
       event.preventDefault(); 
     }; 
     </script> 
    </body> 
</html> 
相关问题