Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)

前端 未结 5 638
一个人的身影
一个人的身影 2020-11-22 00:02

Using ES6 arrow functions with lexical this binding is great.

However, I ran into an issue a moment ago using it with a typical jQuery click binding:

5条回答
  •  梦谈多话
    2020-11-22 00:12

    Another case

    The top answer is correct and I've up-voted it.

    However, there is another case:

    $('jquery-selector').each(() => {
        $(this).click();
    })
    

    Could be fixed as:

    $('jquery-selector').each((index, element) => {
        $(element).click();
    })
    

    This is a historical mistake in jQuery which puts the index, instead of the element as the first argument:

    .each( function )

    function
    Type: Function( Integer index, Element element )
    A function to execute for each matched element.

    See: https://api.jquery.com/each/#each-function

提交回复
热议问题