在没有“可能的严格违规”的函数中使用它。

时间:2015-03-26 18:16:43

标签: javascript jquery this

我正在编写一个在“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说我的变量有“可能的严格违规”。我该如何解决这个问题?

我制作了JSFiddle here


我尝试过的步骤

  1. 如上所述使用.apply(this)here
  2. 将$ this放在函数中,因此可以传入(as mentioned here)

1 个答案:

答案 0 :(得分:2)

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

要实现您的目标,您只需让accordion返回其他功能即可。然后你就拥有了你想要的一切:

    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没问题。