0

我正在使用普通的 HTML 下拉菜单进行测试,但在提交按钮时遇到了问题...

以下是我的代码:

<head>
<script>
function submitButton()
{
var mylist=document.getElementById("myList");
document.getElementById("favorite").innerHTML=mylist.options[mylist.selectedIndex].text;
}
</script>
</head>

<body>
<form>
<select id="myList">
  <option> </option>
  <option>A</option>
  <option>B</option>  
  <option>C</option>
  <option>D</option>
</select>
<button onclick= 'submitButton()'> Submit </button>
<p>You chose: <span id= 'favorite'> </span></p>
</form>
</body>

现在,当我通过 Adob​​e Dreamweaver 中的 Live 运行此代码时,它完全按照我的意愿运行;当我从下拉菜单中选择某些内容并按下提交按钮时,特定字母会出现在“您选择:”之后。

但是,当我在 Google Chrome 和 Safari 中运行它时,结果却有所不同。当我从下拉列表中选择并按“提交”时,该字母会出现在其位置一瞬间,然后页面似乎会自动刷新,下拉列表保持其原始值,并且<span>空白。有谁知道为什么,以及如何解决这个问题?

4

2 回答 2

1

默认情况下<button>,表单中的 a 将提交加载表单的操作 url 的表单,如果没有,则提交相同的页面。
只需将按钮类型更改为按钮,这将阻止它提交表单。

<button type="button" onclick= 'submitButton()'> Submit </button>
于 2014-01-18T18:49:26.217 回答
1

你也可以试试这个

<head>
<script>
function submitButton()
{
var mylist=document.getElementById("myList");
document.getElementById("favorite").innerHTML=mylist.options[mylist.selectedIndex].text;
}
</script>
</head>

<body>
<form>
<select id="myList">
  <option> </option>
  <option>A</option>
  <option>B</option>  
  <option>C</option>
  <option>D</option>
</select>
<input type="button" onclick= 'submitButton()' value="Submit" /> 
<p>You chose: <span id= 'favorite'> </span></p>
</form>
</body>
于 2014-01-18T18:55:24.920 回答