使用JavaScript在下拉列表中保留所选值 [英] with JavaScript Keep selected value in dropdown list

查看:154
本文介绍了使用JavaScript在下拉列表中保留所选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下下拉列表:

Gender<select name="gender"  id="gender"> 
  <option value=" "> EMPTY </option> 
  <option value="Male">Male</option> 
  <option value="Female">Female</option> 
</select>

如果我选择其中一个选项,它应该保持选择为主要选项,即使我更新页。例如,如果我选择男性,下拉列表应该保持男性作为选择的选项,这应该只有当我用鼠标点击它才会改变。如何在JavaScript中执行此操作?

If I choose one of the options, it should stay selected as a primary option even if I renew the page. For example, if I choose Male, the dropdown list should keep Male as a selected option and this should only change when I click on it with the mouse. How to do this in JavaScript?

推荐答案

这是一个javascript / jquery方式,使用localStorage。如果你要在很多地方这样做,可能有办法优化这个代码。

Here's a javascript/jquery way, using localStorage. If you're going to do this in a lot of places there are probably ways to optimize this code.

$(function() {
    var genderValue = localStorage.getItem("genderValue");
    if(genderValue != null) {
        $("select[name=gender]").val(genderValue);
    }

    $("select[name=gender]").on("change", function() {
        localStorage.setItem("genderValue", $(this).val());
    });
})

这篇关于使用JavaScript在下拉列表中保留所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆