在没有 "Possible strict violation." 的函数中使用它

Use this in a function without "Possible strict violation."

我正在编写一个在 'click' 事件上调用的 Jquery 函数。该函数需要使用this,所以它可以引用被点击的元素:

        var allPanels = $('[data-display-mode~="accordion"] .unit-text').hide();
        $('[data-display-mode~="accordion"] .unit').addClass("closed");

        function accordion($this, $type) {
            var $root;
            var $body;
            var $this = $(this);

//Change variables depending on function
            if ($type === "stack") {
                $root = $(this).parents(".unit");
                $body = $(this).parents(".unit").find('.unit-text');
            } else if ($type === "panel") {
                $root = $(this);
                $body = $(this).find('.unit-text');
            }

            if ($root.hasClass('closed')) {
                allPanels.slideUp().parents(".unit").removeClass('open').addClass('closed');
                $root.removeClass('closed').addClass('open');
                $body.slideDown();
            } else {
                $root.removeClass('open').addClass('closed');
                $body.slideUp();
            }
        }

        // Call function on Click
        $('[data-display-mode~="accordion"][data-display-mode~="stack"] .unit-heading').click(accordion("stack"));
        $('[data-display-mode~="accordion"][data-display-mode~="panel"]').click(accordion("panel"));
    });

我该怎么做?此外,JSlint 说我的变量有 "Possible strict violation"。我该如何解决这个问题?

我做了一个JSFiddle here


我试过的步骤

  1. 如前所述使用 .apply(this) here.
  2. 将$this放在函数中,这样就可以传入(as mentioned here)

重要的是要知道 .click 需要函数引用。您正在做的是调用一个不 return 任何函数引用的函数。

要实现你想要的,你可以简单地使 accordion return 成为另一个功能。然后你就会拥有你想要的一切:

    function accordion($type) { //Removed the $this argument
        return function(){ //That will be the function called when you click on the target
            var $root;
            var $body;
            var $this = $(this);

            //Change variables depending on function
            if ($type === "stack") {
                $root = $(this).parents(".unit");
                $body = $(this).parents(".unit").find('.unit-text');
            } else if ($type === "panel") {
                $root = $(this);
                $body = $(this).find('.unit-text');
            }

            if ($root.hasClass('closed')) {
                allPanels.slideUp().parents(".unit").removeClass('open').addClass('closed');
                $root.removeClass('closed').addClass('open');
                $body.slideDown();
            } else {
                $root.removeClass('open').addClass('closed');
                $body.slideUp();
            }
        }
    }

Fiddle

如果您检查控制台,您会发现 $type 没问题。