問題描述
在我的網(wǎng)站上,用戶可以按流派過濾游戲.當用戶從選擇框中選擇一種類型并點擊提交時,頁面使用 GET 來查看過濾器是什么.現(xiàn)在過濾器工作正常,問題是選擇框的選擇變?yōu)槟J選擇(即全部".)
On my website, user's are allowed to filter games by Genre. When a user chooses a genre from the select box and hits submit, the page uses GET to see what the filter was. Now the filter works fine, the problem is that the select box's selection goes to the default one (Which says "All".)
我希望在用戶提交過濾請求后,選擇框將在頁面重新加載后保留該選擇.
I want it so that after a user submits their filter request, the select box will keep that selection after the page reloads.
我只能想到一種方法來做到這一點,但它需要將 PHP 添加到每個選項中.有沒有更簡單的方法可以用 PHP 或 jQuery 來做到這一點?
There's only one way I could think of to do this but it would require adding in PHP into every option there is. Are there any simpler ways to go about doing this with PHP or jQuery?
推薦答案
假設你正在做一個完整的表單提交,選擇的選項只會對服務器端代碼可用,一旦它返回給客戶端使用 jQuery 你不會有那個(除非你在表單提交之前嘗試使用 cookie,但是 bleh).
Assuming you're doing a full form submit the selected option is only going to be available to the server-side code, once it gets back to the client to use jQuery you won't have that (unless you try to use cookies before the form submit, but bleh).
我會在選項標簽中使用 PHP,如果選項與所選選項匹配,則回顯 selected="selected"
.
I'd use PHP in the option tag and echo selected="selected"
if the option matches up with the selected option.
如果你想避免大量重復的代碼,為什么不做這樣的事情:
If you want to avoid a lot of duplicated code why not do something like this:
<select name="test">
<?php
$options = array(1 => 'Option 1', 2 => 'Option 2', 3 => 'Option 3');
foreach ($options as $key => $value) {
echo '<option value="' . $key . '"' . ($key == $_GET["test"] ? ' selected="selected"' : '') . '>' . $value . '</option>';
} ?>
</select>
這篇關于提交后保持選中的選擇框的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!