[英]Form Submission Goes To Javascript - And Stay On Same Page
請考慮以下無效的HTML文檔:
<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鍵;或 然后會使用s文本輸入的內容來調用函數f-否則,在f返回后,瀏覽器應停留在同一頁面上。
我該如何實現?
您應該使用提交輸入而不是按鈕輸入,並且要從文本輸入中獲取文本,請使用value屬性,並返回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>
只是用值而不是表單元素來調用它?
onsubmit="return f(this.bar.value);"
為了防止發送該頁面,您可以從f
返回false
。
但是,使用適當的事件處理程序代替onsubmit-attribute會更加干凈。 在這里閱讀更多關於它們的信息 。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.