首页 > 解决方案 > 保存所选选项不适用于 jquery

问题描述

我需要保存用户的选择..这样做:

$(".dateTimeFilterIdentifierCls").change(function () {
    debugger;
    localStorage.setItem('ChosenDateIndexLS', $(".dateTimeFilterIdentifierCls").find(":selected")[0].index);

});

$(document).ready(function () {

    console.log("ChosenDateIndexLS is :: ", localStorage.getItem('ChosenDateIndexLS'));
    $(".dateTimeFilterIdentifierCls").prop('selectedIndex', localStorage.getItem('ChosenDateIndexLS')); 
});

在 aspx 页面中使用的 css 类:

  <td height="21" width="343" colspan="2" style="width: 614px;">
                        <asp:UpdatePanel ID="showsDatalistPanel" runat="server" Visible="false" UpdateMode="Always">
                            <ContentTemplate>
                                <div>
                                    <asp:DropDownList ID="dateTimeFilter" CssClass="dateTimeFilterIdentifierCls" runat="server" OnSelectedIndexChanged="dateTimeFilter_SelectedIndexChanged"
                                        onchange="bindControlEvents()" AutoPostBack="true" Visible="false">
                                    </asp:DropDownList>
                                    <label id="dateTimeFilterLabel" runat="server" style="padding-left: 15px" visible="false">
                                        בחירת מופע לפי תאריך</label>
                                </div>

还尝试使用以下方法保存索引:

$(".dateTimeFilterIdentifierCls").change(function () {
    localStorage.setItem('ChosenDateIndexLS', $(".dateTimeFilterIdentifierCls").val());
});

他们都不工作。真的需要一个解决方案。谢谢!

标签: javascriptjqueryasp.netaspx-user-control

解决方案


像这样尝试,在谷歌浏览器中工作,我正在注销本地存储,这样你就可以看到它保存了选择。在您的示例中,您已准备好文档之外的 on change,因此 on change 可能无法正确触发或根本无法触发

代码

<!DOCTYPE html>
  <html lang="en" dir="ltr">
    <head>
    <meta charset="utf-8">
    <title></title>
    <script
      src="https://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous">
    </script>
    </head>
    <body>
      <select class="dateTimeFilterIdentifierCls" name="">
        <option value="hi"> hi </option>
        <option value="hello">hello</option>
        <option value="foo">foo</option>
        <option value="bah">bah</option>
      </select>
    </body>
    <script type="text/javascript">
    $().ready(function(){
      $('.dateTimeFilterIdentifierCls').change(function(){
        localStorage.setItem('ChosenDateIndexLS',$(".dateTimeFilterIdentifierCls").val());
        console.log(localStorage);
      });
    });
    </script>
  </html>

推荐阅读