jQuery uses each method to traverse objects

The implicit iteration of jquery will set the same value for all DOM objects, but if we need to set every object that is not worth it, we need to iterate ourselves

each method

$(selector).each(function(index,element){})

Each() method can pass a function, and the function can pass two parameters

Parameter 1: Indicates the index number of the current element among all matched elements

Parameter 2: Represents the current element (DOM)

Case: Set different transparency for different li
 <div>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
      </ul>
    </div>

    // 方法1:
    for(let i = 0;i<$('li').length;i++){
    
    
      $('li').eq(i).css('opacity',(i+1)/10);
    }

    // 方法2:(推荐)
    $('li').each(function(index,element){
    
    
      $(element).css('opacity',(index+1)/10)
    })
Web front-end communication QQ group: 327814892

Guess you like

Origin blog.csdn.net/qq_43327305/article/details/103241436