我试图基于data属性(在本例中为data-filter)触发点击页面加载。我将属性的值保存在本地存储中。我检索了它,但是我不确定如何定位具有该属性的特定列表项。
例如,如何确定本地存储是否返回.portfolio-category-1?
预先感谢
/* on click do this */
$(".edgtf-pl-filter").click(function() {
var isFilter = $(this).data("filter");
localStorage.setItem('pod-filter', isFilter);
alert(isFilter);
});
/* On page load, do this */
var isFilterRet = localStorage.getItem('pod-filter');
setTimeout(function() {
$(".edgtf-pl-filter").trigger('click');
}, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="edgtf-pl-filter" data-filter="">
<span>all</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-1">
<span>Categroy 1</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-2">
<span>Category 2</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-3">
<span>Category 3</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-4">
<span>Category 4</span>
</li>
</ul>
答案 0 :(得分:0)
我不确定我是否正确理解您的意思。您只是要在变量isFilterRet中存储哪个名称/类的元素上触发什么?
尝试一下:
seen
答案 1 :(得分:0)
这将为您工作:
我添加了一个.each()
函数来检查所有.edgtf-pl-filter
并使用localStorage
标识元素并触发一个click()
。
我已删除了setTimeout()
函数,因为它不是必需的
/* on click do this */
$(".edgtf-pl-filter").click(function() {
var isFilter = $(this).data("filter");
localStorage.setItem('pod-filter', isFilter);
alert(isFilter);
});
/* On page load, do this */
var isFilterRet = localStorage.getItem('pod-filter');
$(".edgtf-pl-filter").each(function() {
var atrFil = $(this).data("filter");
if (atrFil == isFilterRet) {
$(this).trigger('click');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="edgtf-pl-filter" data-filter="">
<span>all</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-1">
<span>Categroy 1</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-2">
<span>Category 2</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-3">
<span>Category 3</span>
</li>
<li class="edgtf-pl-filter" data-filter=".portfolio-category-4">
<span>Category 4</span>
</li>
</ul>
working fiddle来检查其是否正常运行。
希望这对您有所帮助。