简体   繁体   English

将“ this”传递给JavaScript的正确方法

[英]Correct way to pass 'this' to function in javascript

My javascript is pretty basic so I though I'd ask the experts as to whether my current method is right or not, and if there are better, more accepted ways. 我的javascript很基础,因此尽管我会问专家我当前的方法是否正确,以及是否有更好,更可接受的方法。

Normally I would use jquery's .on event to trigger a function, like this: 通常我会使用jquery的.on事件来触发一个函数,如下所示:

$("body").on("input", "textarea", textareaAutoGrow);

function textareaAutoGrow() {
    var pad = $(this).outerHeight(false) - $(this).innerHeight();

    this.style.height = "auto";
    this.style.height = (this.scrollHeight + pad) + "px";
}

This way, 'this' is passed automatically, however I now need to do the same thing on the window resize event for all textareas, not just one specific one. 这样,“ this”会自动传递,但是我现在需要对所有textarea的窗口调整大小事件执行相同的操作,而不仅仅是一个特定的。

Here's how I've done it: 这是我的操作方法:

$(window).on("resize", refreshAutoGrow);

function refreshAutoGrow() {
        $el = $(".text-field.autogrow").filter(function () {
            return $(this).val();
        });

        $el.each(function () {
            textareaAutoGrow.call(this);
        });
    }

I've called the textareaAutoGrow function using .call - something I picked up from looking at jquery widgets. 我使用.call调用了textareaAutoGrow函数,这是我从查看jquery小部件中获得的东西。

It works but as I said, it's very much a guess - is this the right approach, or are there more accepted ways of doing what I want? 它行得通,但是正如我所说,这是一个很大的猜测-这是正确的方法,还是有更多可接受的方式来完成我想要的事情?

Trigger it with each on resize to loop the textareas: each调整大小时触发它以循环文本区域:

function textareaAutoGrow() {
    var pad = $(this).outerHeight(false) - $(this).innerHeight();

    this.style.height = "auto";
    this.style.height = (this.scrollHeight + pad) + "px";
}

$("body").on("input", "textarea", textareaAutoGrow);
$(window).on("resize", funtion() {
    $("textarea").each(textareaAutoGrow);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM