jquery: Toggle elements based on result from a function
I have a number of table rows that I would like to toggle the visibility of. They should be visible if a data item I have set on them earlier equals a selected value in a form. This is what I have so far:
$('#category-selector').change(function(event)
{
var category_id = $(this).val();
if(!category_id)
{
$('tr', '#table tbody').show();
}
else
{
$('tr', '#table tbody').toggle();
}
});
Of course this just toggles them on and off. Thing is that I thought I was able to give toggle
a function that would decide if each row should be on or off, but it turns out I 开发者_运维百科can only give it a boolean condition which would be an all or nothing deal kind of...
So, I have this function:
function()
{
return $(this).data('category_id') == category_id;
}
How can I use that to go through all the rows and toggle them on or off? Or is there a better approach to this? What should I do?
$('#category-selector').change(function(event)
{
var category_id = $(this).val();
$('tr', '#table tbody').toggle($(this).data('category_id') == category_id);
});
Still curious if there are better or smoother or faster ways of doing this, but this is how I have done it now:
else
{
$('tr', '#table tbody').each(function()
{
$(this).toggle( $(this).data('category_id') == category_id );
});
}
精彩评论