根据data-*属性显示和隐藏元素

Chr*_*ski 3 jquery show-hide custom-data-attribute

这似乎对JQuery来说应该是微不足道的,但是这个函数隐藏了整个表单......有人能指出我正确的方向吗?

$('form')
        .children()
        .filter(function(){
            return $(this).data('show', 'pro')
        })
        .show();
$('form')
         .children()
         .filter(function(){
             return $(this).data('show', 'home')
         })
         .hide();
Run Code Online (Sandbox Code Playgroud)

Jos*_*ber 8

您将2个参数传递给该data方法,从而设置它而不是检索旧值.

请改用:

$('form')
        .children()
        .filter(function(){
            return $(this).data('show') === 'pro';
        })
        .show();
$('form')
         .children()
         .filter(function(){
             return $(this).data('show') === 'home';
         })
         .hide();
Run Code Online (Sandbox Code Playgroud)

您还可以缓存选择器的性能(或使用end).


jfr*_*d00 6

如果数据显示值在HTML中或在每个对象上设置为属性,则可以使用选择器完全执行此操作:

$('form > [data-show="pro"]').show();
$('form > [data-show="home"]').hide();
Run Code Online (Sandbox Code Playgroud)

作为解释:

  • form明显选择表单元素
  • 所述>选择所述形式对象的子
  • [data-show="pro"]只选择具有名为属性的孩子data-show被设置为值"pro"
  • .show()呼叫在这些选定的对象显示方法

如果您的数据显示值是使用.data()jquery方法设置的,那么之前的方法将不起作用,那么您最好将状态设置为类名,而不是可以更容易在选择器中使用的数据值.如果将这些值设置为类名而不是数据,则代码如下所示:

$('form > .pro').show();
$('form > .home').hide();
Run Code Online (Sandbox Code Playgroud)

请记住,您可以在对象和对象状态上拥有多个类名,这些类直接用于控制对象的表示(CSS样式,可见性,格式等等),更好地表示为类名而不是数据-xxx属性,因为在CSS或jQuery操作的选择器中使用它更容易.