基于 .data() 键/值的过滤器元素 [英] Filter element based on .data() key/value
问题描述
假设我有 4 个带有 .navlink
类的 div 元素,当点击它们时,使用 .data()
来设置一个名为 'selected'
,为 true
的值:
Say I have 4 div elements with class .navlink
, which, when clicked, use .data()
to set a key called 'selected'
, to a value of true
:
$('.navlink')click(function() { $(this).data('selected', true); })
每次点击一个新的.navlink
时,我都想存储之前选择的navlink
以供以后操作.是否有一种快速简便的方法可以根据使用 .data()
存储的内容来选择元素?
Every time a new .navlink
is clicked, I would like to store the previously selected navlink
for later manipulation. Is there a quick and easy way to select an element based on what was stored using .data()
?
似乎没有任何符合要求的 jQuery :filters,我尝试了以下操作(在同一个点击事件中),但由于某种原因它不起作用:
There don't seem to be any jQuery :filters that fit the bill, and I tried the following (within the same click event), but for some reason it doesn't work:
var $previous = $('.navlink').filter(
function() { $(this).data("selected") == true }
);
我知道还有其他方法可以做到这一点,但现在我主要只是好奇是否可以通过 .data()
来完成.
I know that there are other ways to accomplish this, but right now I'm mostly just curious if it can be done via .data()
.
推荐答案
您的过滤器可以工作,但是您需要在传递给过滤器的函数中匹配对象时返回 true,以便过滤器抓取它们.
your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.
var $previous = $('.navlink').filter(function() {
return $(this).data("selected") == true
});
这篇关于基于 .data() 键/值的过滤器元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!