实际上,我想在单击标签时为 anchor 标签添加类,但它在页面加载时隐藏。就我而言,我想在加载后刷新页面,它还应该为单击的内容添加类。如何解决这个问题?
代码(使用 JQuery):
$(".category_filter").click(function() {
// alert("coming");return false;
$(this).addClass('selected');
//return false;
});
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<div class="flDropDiv category_fl">
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/full-bed-sheets"> Full bed sheets </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/fitted-bed-sheet"> Fitted bed Sheet </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/flat-bed-sheet"> Flat bed sheet </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/twin-bed-sheet"> Twin bed sheet </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/twinxl-bed-sheets"> Twinxl bed sheets </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/queen-bed-sheet"> Queen bed sheet </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/king-bed-sheets"> King bed sheets </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/cal-king-bed-sheets"> Cal king bed sheets </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/duvet-covers"> Duvet covers </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/bed-skirts"> Bed skirts </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/standard-pillow-cases"> Standard Pillow cases </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/king-pillow-cases"> King Pillow cases </a> </div>
<div class="flItems"><a class="category_filter" href="http://192.168.1.156/eles/bed-linen/pillow-shells"> Pillow shells </a> </div>
</div>
最佳答案
比较 href
与 window.location.href
您可以将当前的 window.location.href
与链接的 href
进行比较。
这不需要任何cookie、localStorage、webSQL 或任何东西。
$( document ).ready(function() {
$('.flItems a.category_filter').each(function() {
// Comparing the href attribute to see if this is the selected page
if ($(this).prop('href') === window.location.href) {
$(this).addClass('selected');
}
});
});
这可能是您的意图,只需突出显示当前页面即可。
从未点击过其中一个链接的用户将不会在导航中看到所选内容。
无论他们如何使用您的网站,上述解决方案都将有效(当然,前提是启用了 JavaScript)。
关于javascript - 如何记住页面刷新时的CSS类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42291283/