当我点击一个'a‘链接时,我正在努力添加一个使用jquery和localStorage的’活动‘类。
这是我正在使用的布局:
<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>这是JS:
jQuery(document).ready(function($) {
$(function () {
$('.order-by').click(function () {
$('.order-by > img').siblings().removeClass('active-order');
$('.order-by > img').addClass('active-order');
var activeIndex = $(this).index();
localStorage.setItem('mySelectValue', activeIndex);
});
});
jQuery(document).ready(function($) {
var activeIndex = localStorage.getItem('mySelectValue');
if (isNan(activeIndex)) {
console.log('nothing stored');
} else {
$('.order-by > img').addClass('active-order');
}
});这背后的想法是,当点击正确的'a‘链接时,底层的img会得到一个活动的类(只是bg颜色)。因为浏览器会在点击时刷新,所以我使用localStorage在下一次加载时使用它……我在这里做错了什么?
发布于 2016-04-14 11:05:50
正如@Andrew Dunai所说,在从本地存储读取时,您应该检查是否为空。
$('.order-by > img').siblings().removeClass('active-order');
在这一行中,您将从图像的兄弟项中删除类,而不是从实际的图像中删除类,因此删除.siblings()。
当您从本地存储读取并尝试将类添加到活动订单时,您正在选择每个图像。您需要指定一个与本地存储中存储的索引相匹配的特定索引。我在这里使用的是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 because there is a span at index 0
https://stackoverflow.com/questions/36612222
复制相似问题