Javascript 使用localStorage添加活动类
当点击“a”链接时,我正在努力使用jquery和localStorage添加一个“活动”类 这是我正在使用的布局:Javascript 使用localStorage添加活动类,javascript,jquery,html,Javascript,Jquery,Html,当点击“a”链接时,我正在努力使用jquery和localStorage添加一个“活动”类 这是我正在使用的布局: <div class="ordering-box" style="display: inline-block;"> <?php $order_method = JRequest::getVar("orderto", ""); ?> <?php $order_method = $moduleParams-
<div class="ordering-box" style="display: inline-block;">
<?php $order_method = JRequest::getVar("orderto", ""); ?>
<?php $order_method = $moduleParams->ordering_default_method; ?>
<span class="ordering-box-text">chronologisch</span>
<a class="order-by" href="#" onclick="document.K2Filter<?php echo $moduleId; ?>.orderto.value='asc'; submit_form_<?php echo $moduleId; ?>(); return false;">
<img class="ph" src="<?php echo JURI::base()."templates/template-src"?>/images/icons/chevron-down.png">
</a>
<a class="order-by" href="#" onclick="document.K2Filter<?php echo $moduleId; ?>.orderto.value='desc'; submit_form_<?php echo $moduleId; ?>(); return false;">
<img class="active-order" src="<?php echo JURI::base()."templates/template-src"?>/images/icons/chevron-up.png">
</a>
</div>
这背后的想法是,当点击正确的“a”链接时,底层img会得到一个活动类(只是一个bg颜色)。因为浏览器会在单击时刷新,所以我正在使用localStorage在下一次加载时进行更新。。。我在这里做错了什么?正如@Andrew Dunai所说,当从本地存储读取数据时,应该检查null
$('.order by>img').sides().removeClass('active-order')代码>
在这一行中,您将从映像的同级中删除类,而不是从实际映像中删除类,因此请删除.sibles()
当您从本地存储读取并尝试将类添加到活动顺序时,您选择的是每个图像。您需要指定与本地存储中存储的索引匹配的特定索引。我在这里使用eq()
if (activeIndex === null) {
console.log('nothing stored');
} else {
$('.order-by > img').removeClass('active-order'); // remove active class from all
$('.order-by').eq(activeIndex).find('img').addClass('active-order'); // add class to specified order
}
此外,在存储索引时,您需要注意,span.ordering box text
将位于索引0处,因此您应该将索引减少1
localStorage.setItem('mySelectValue',$(this.index()-1);//-1,因为索引0处有一个跨度
isNan
错误,您应该使用isNan
。检查控制台是否有错误。此外,在这里使用isNaN
是不正确的:您应该检查null
,因为如果没有存储值,它将返回。另外,将$('.order by>img')
替换为$('.order by>img').eq(activeIndex)
。
if (activeIndex === null) {
console.log('nothing stored');
} else {
$('.order-by > img').removeClass('active-order'); // remove active class from all
$('.order-by').eq(activeIndex).find('img').addClass('active-order'); // add class to specified order
}