2011-04-21 116 views

回答

1

頁面本身沒有狀態,並且不會記住用戶在重新加載時所做的任何操作。

如果您也使用服務器端語言,那麼您可以將該值保存在服務器上的某個位置(數據庫或簡單平面文件),但是如果您只有javascript並且無法將值保存到服務器上可以查看saving the value to a cookie,然後在頁面重新加載時恢復該值。

如果你覺得真的很冒險,HTML5還可以讓你將內容保存到local storage之類的東西,儘管只有更高級的瀏覽器才支持。

0

您可以使用$ _GET發送和檢索選擇框狀態。

Live Demo

代碼:

<form> 
    Select Option:<br /> 
    <select name="foo" id="foo"> 
    <?php echo_select(10); ?> 
    </select> 
    <input type="submit" name="submit" Value="Do location.href" onclick='return do_foo();' /> 
</form><br /> 
Press Button and on page-load, your selected value will be pre/auto-selected. 

<script type=text/javascript> 
    function do_foo(){ 
    var foo = document.getElementById('foo').value; 
    //alert("location.href is: "+document.URL+"var="+foo); 
    window.location.href = document.URL+"var="+foo; 
    return false; 
    } 
</script> 

<?php 
//print_r($_GET); 

function echo_select($number){ 
    for($i=0;$i<$number;$i++){ 
     echo "<option value=".($i+1); 
     if(isset($_GET["var"]) && ($_GET["var"]==($i+1))){ 
      echo " selected=\"selected\""; 
     } 
     echo ">Text ".($i+1)."</option>"; 
    } 
} 
?> 

當然這個片段假定您使用PHP來生成表單代碼。但是讓我知道你是否以不同的方式生成和處理你的表單。

相關問題