gpt4 book ai didi

javascript - 当选项更改并且我需要重新加载页面时,如何保持该选项处于选中状态?

转载 作者:行者123 更新时间:2023-12-03 05:21:15 24 4
gpt4 key购买 nike

我有以下 HTML 选择:

<select class="form-control" id="band_id" name="band_id">
<option selected="selected" value="">Choose a band...</option>
<option value="66">Adolfo Little</option>
<option value="96">Aisha Bosco</option>
<option value="90">Alize Glover</option>
</select>

我需要构建一个过滤器,其中条件是所选的#band_id,因此我编写了以下 jQuery 代码:

$("select#band_id").change(function (ev) {
ev.preventDefault();
var band_id = $('select#band_id');

if (band_id.val() != undefined) {
band_id.attr('selected', 'selected');
}

location.href = '/albums/bands/' + band_id.val();
});

因为 location.href 页面被重新加载并且 URL 发生变化,因此 SELECT 被重置并且我“释放”了所选值。

我可以考虑用两种方法来解决这个问题:

  • 使用我不想要的 AJAX,因为它让简单的事情变得过于复杂
  • 从 URL 中获取 band_id,然后设置选定的属性,但我不知道如何实现。

不知道还有没有其他方法可以达到这个目的。你还有其他想法吗? (如果有例子就更好了)

最佳答案

您可以使用localStorage为此:

if (localStorage.getItem("band_id")) {
$("select#band_id").val(localStorage.getItem("band_id"))
}
$("select#band_id").change(function (ev) {
ev.preventDefault();

if ($(this).val() != undefined) {
$(this).attr('selected', 'selected');
localStorage.setItem("band_id", $(this).val());
}

location.href = '/albums/bands/' + $(this).val();
});

如果我们保存了该值 - 将 select 元素的值设置为该值。
一旦我们更改了 select 元素中的值 - 将新值保存在 localStorage 中。

Note that I removed the usage of the band_id from this example as it's not needed. You have this you can use inside the change function.

I'm also not sure why you change the selected attribute - you redirect the user immediately to a new page (this change will have no effect at all).

关于javascript - 当选项更改并且我需要重新加载页面时,如何保持该选项处于选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com