【问题标题】:Use this in a function without "Possible strict violation."在没有“可能严格违反”的函数中使用它。
【发布时间】:2015-05-30 21:52:23
【问题描述】:

我正在编写一个在“点击”事件上调用的 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)

【问题讨论】:

标签: javascript jquery this


【解决方案1】:

重要的是要知道.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 没问题。

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 2015-12-05
    • 2014-05-17
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2016-06-18
    • 2012-07-24
    相关资源
    最近更新 更多