programing

.trigger () 대 .click ()의 ​​jQuery 장점 / 차이점

nasanasas 2020. 11. 12. 08:19
반응형

.trigger () 대 .click ()의 ​​jQuery 장점 / 차이점


성능 측면에서 다음과 같은 이점 (또는 차이점)은 무엇입니까?

$('.myEl').click();

$('.myEl').trigger('click');

전혀 없습니까?


다음은 click메서드 의 코드입니다 .

jQuery.fn.click = function (data, fn) {
    if (fn == null) {
        fn = data;
        data = null;
    }

    return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click");
}

보시다시피; 함수에 인수가 전달되지 않으면 클릭 이벤트가 트리거됩니다.


사용 .trigger("click")하면 함수가 하나 더 적게 호출됩니다.

그리고 @Sandeep이 그의 대답 에서 지적했듯이 .trigger("click")더 빠릅니다.


1.9.0부터 확인 data기능 fn으로 이동되었습니다.on .

$.fn.click = function (data, fn) {
    return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click");
}

내 생각에는

$('.myEl').trigger('click');

그 기능을 호출하는 것처럼 함수 호출을 저장하기 때문에 더 좋습니다 $('.myEl').click();. jQuery 소스의 코드 살펴보기

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        if ( fn == null ) {
            fn = data;
            data = null;
        }

        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
                    //here they call trigger('click'); if you provide no arguments
            this.trigger( name );
    };

    if ( jQuery.attrFn ) {
        jQuery.attrFn[ name ] = true;
    }

    if ( rkeyEvent.test( name ) ) {
        jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
    }

    if ( rmouseEvent.test( name ) ) {
        jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
    }
});

for performance kind .check here.. http://jsperf.com/trigger-vs-not-trigger Both are almost same...click() is shorthand of trigger('click').


Check http://api.jquery.com/click/ :

In the third variation, when .click() is called without arguments, it is a shortcut for .trigger("click").

It seems they are the same.

참고URL : https://stackoverflow.com/questions/9666471/jquery-advantages-differences-in-trigger-vs-click

반응형