0

我想用开按钮进入不同的房间。这在Javascript中怎么可能。例如,有三个房间,“厨房、卫生间和卧室”。根据我的选择,我如何使用 JS 进入这些房间中的任何一个。因此,如果我在输入框中输入“厨房”,它将带我到 kitchen.php,如果我输入厕所……同一个按钮将带我到厕所.php 等。

这是 HTML 输入,

<form method="post">
<input style=""name="Text1" type="text"><br>
<input name="move" style="height: 23px" type="submit" value="Move">
</form>
4

1 回答 1

1

只需使用选择字段jsfiddle 演示

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
<title>Untitled 1</title> 
<script type="text/javascript"> 
function submitForm() {
    var myform = document.getElementById('myform');
    var mytext = document.getElementById('room');
    myroom = mytext.value.toLowerCase();
    if (myroom == 'kitchen') {
        myform.action = 'kitchen.php';
        myform.submit();
    } else if (myroom == 'toilet') {
        myform.action = 'toilet.php';
        myform.submit();
    } else if (myroom == 'bedroom') {
        myform.action = 'bedroom.php';
        myform.submit();
    } else return false;
}

window.onload = function(){
     document.getElementById('move').onclick = submitForm;
}
</script> 
</head> 

<body> 
<form id="myform" name="myform" method="post"> 
    <input type="text" id="room" name="room" />
     <button id="move" name="move" style="height: 23px">Move</button> 
</form> 
</body> 
</html> 

在 php 端创建三个文件来测试是否可行,toilet.php、kitchen.php 和卧室.php,在所有三个文件中使用以下代码。确保文件名小写:

<?php
echo $_POST['room'];
?>

基本上,根据选择的选项,JavaScript 会更改表单的操作 url 并提交。如果没有选择,它将返回 false 并且不提交。submitForm 函数通过 onclick 事件附加到移动按钮。

于 2011-03-05T23:20:49.773 回答