【问题标题】:Jquery Mobile Filter system, can't hide multiple divsJquery Mobile Filter系统,不能隐藏多个div
【发布时间】:2015-12-11 19:09:21
【问题描述】:

我正在制作一个 Jquery Mobile 应用程序,并且有一个包含 15 个左右带有类的 div 的页面,我正在尝试制作一个过滤系统,以便当您按下按钮时,这些 div 中的一些会根据类消失。有 3 个组,它们都有一个“全部”类来显示所有内容,总共 4 个类。

不幸的是,即使我为 jquery mobile 设置了一个 jsfiddle,当我将它放入我的应用程序时,我使用的大多数 js 也无法正常工作。

我想用

function show(target) {
    document.getElementsByClassName(target).style.display = 'block';
    }
function hide(target) {
    document.getElementsByClassName(target).style.display = 'none';
    }

但这不起作用,而 document.getElementById 似乎工作正常。但是显然我只能隐藏/显示每个按钮 1 个 div..

我想知道是否有解决此问题的方法或我应该尝试一些完全不同的方法?

这是我所拥有的 jsfiddle:http://jsfiddle.net/tzcx7gky/ 它在 jsfiddle 中完全损坏,但在我的代码中运行良好,这很奇怪..

【问题讨论】:

    标签: javascript jquery html jquery-mobile filter


    【解决方案1】:

    您不需要单独的 hide - show 函数。以下将照顾所有。

    $('a').on("click",function()
    {
       $("#scroll_content div").hide(); // initially hide all divs inside the element with id = scroll_content
       var target = $(this).text().toLowerCase(); // find the class you wish to show using the text of the a tag clicked ( I would prefer using data-attr in this case but I'll leave the choice upto you.
         $("." + target).show(); // show the element with the class target.
    });
    

    工作示例:http://jsfiddle.net/tzcx7gky/2/

    【讨论】:

    • 谢谢,这正是我想要的。但是,它似乎仅在 jsfiddle 中不适用于我的代码,我可能有不同的版本吗? Here's 我的 js 中的所有文件,如果它有助于识别版本..
    • 您可能缺少 document.ready 来定义事件委托。 jsfiddle.net/tzcx7gky/7
    • 当然。很高兴帮助:)
    【解决方案2】:

    getElementsByClassName 返回一个元素数组。因此,您必须遍历数组,然后在每个数组上设置 display 属性。由于您已经在使用 jQuery,因此您可以使用它来处理所有元素。

    function show(target) {
        /* jQuery uses CSS selectors to grab elements
           so we have to prefix the target with "."
           Alternativley we could pass in the whole selector in the
           function so we don't have to prefix it e.g.
           show('.all')
           $(target).show();
        */
        $("."+target).show();
    }
    function hide(target) {
        $("."+target).hide();
    }    
    

    这是 vanilla js 框架中的相同实现

    function show(target) {
        var elements = document.getElementsByClassName(target);
        elements.forEach(function(element){element.style.display = 'block';});
        }
    function hide(target) {
        var elements = document.getElementsByClassName(target);
        elements.forEach(function(element){element.style.display = 'none';});
        }
    

    请注意,getElementById 返回单个元素,因为 id 是唯一的,并且页面上应该只有一个具有一个 id 的元素。这就是为什么它对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      相关资源
      最近更新 更多