在没有“;可能存在严重违规行为&”;

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

本文关键字:存在      更新时间:2023-09-26

我正在编写一个Jquery函数,该函数在"click"事件上调用。该函数需要使用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


我尝试过的步骤

  1. 使用此处提到的.apply(this)
  2. 将$this放入函数中,以便可以传入(如这里所述)

需要知道的是.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正常。