简体   繁体   English

通过jQuery中的列表项值选择的预填充列表项

[英]Pre fill list item selected by list item value in jquery

I'm new to JQuery. 我是JQuery的新手。 In my App I have the following: 在我的应用程序中,我具有以下内容:

My HTML code is here.. 我的HTML代码在这里。

<ul id="list">
    <li>
        <a class="selected" value="0" href="#"  id="sel">ALL</a>
    </li>
    <li>
        <a href="#"  value="1">1+</a>
    </li>
    <li>
        <a href="#" value="2">2+</a>
    </li>
    <li>
        <a href="#" value="3">3+</a>
    </li>
    <li>
        <a href="#" value="4">4+</a>
    </li>
    <li>
        <a href="#" value="5">5+</a>
    </li>
</ul>

<input type="hidden" id="hdn_list" value=""></input>

My CSS code is here.. 我的CSS代码在这里。

.selected{background-color:green;}

My JQuery code for getting the selected list value is here.. 我的用于获取所选列表值的JQuery代码在这里。

$(document).ready(function () {
    $('#list li a').click(function () {
        var new = $(this).attr("value");
        $("#hdn_list").value = new;          //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    });
});

When i am clicking the submit button it is redirected to next page.. if i back to this page again it must pre fill the selected value using that hidden control(#hdn_list) value and the css style also must apply that selected value.. how to do this through jquery/javascript? 当我单击“提交”按钮时,它将重定向到下一个页面。如果再次回到此页面,它必须使用该隐藏控件(#hdn_list)值预先填充所选值,并且CSS样式也必须应用该所选值。如何通过jquery / javascript做到这一点? thanks in advance. 提前致谢。

Use event.preventDefault() in jquery. 在jquery中使用event.preventDefault() it's stop the default action 停止默认动作

$(document).ready(function () {
    $('#list li a').click(function (event) {
      event.preventDefault();
        var new = $(this).attr("value");
        $("#hdn_list").value = new;          //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');

    });
});

Try this 尝试这个

 $(document).ready(function () {
    $('#list li a').click(function (e) {
        var nvalue = $(this).attr("value");
        localStorage.setItem("menu", nvalue);
        $("#hdn_list").val(nvalue); //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');
        e.preventDefault();
    });
      var retrievedObject = localStorage.getItem('menu');
      if (retrievedObject != null) {
        $('ul li a').removeClass("selected")
        $('ul li a[value="' + retrievedObject +'"]').addClass('selected');
      } else {
        $('ul li a:eq(0)').addClass('selected');
      }
});

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM