使用具有特定'数据-*'

Call function on class with elements that has certain 'data-*'

本文关键字:数据      更新时间:2023-12-10

假设我有以下html:

<img onclick="showStruct(this)" class="expand" src="Images/Plus.png" data-hidden="true" style="display: none;">
<img onclick="showStruct(this)" class="expand" src="Images/Plus.png" data-hidden="false" style="display: inline;">
<img onclick="showStruct(this)" class="expand" src="Images/Plus.png" data-hidden="true" style="display: none;">

如果元素被隐藏,我会将true存储在data-hidden字段中,因为我必须同时隐藏所有元素,并且通过将"状态"存储在data-hidden字段中,我确保我知道要再次显示哪些元素。即:

<img onclick="showStruct(this)" class="expand" src="Images/Plus.png" data-hidden="true" style="display: none;">
<img onclick="showStruct(this)" class="expand" src="Images/Plus.png" data-hidden="false" style="display: none;">
<img onclick="showStruct(this)" class="expand" src="Images/Plus.png" data-hidden="true" style="display: none;">

我想做的是,通过使用jquery,只为具有data-hidden: 'false'的元素设置display: inline;

我所拥有的(有效的):

$(".expanded").each
    (function() {
        if($(this).attr('data-hidden')=='false'){
            $('.expanded').show();
        }
    });

我的问题是,有更好(更有效)的方法吗?还是这是唯一的方法?

您可以简单地使用属性选择器

$('.expanded[data-hidden="false"]').show()

演示:Fiddle

试试这个,

$(".expanded").filter(function(){
   return $(this).data('hidden') == 'false';
}).show();