source

jQuery는 같은 클래스의 요소를 루프합니다.

nicesource 2022. 11. 4. 21:29
반응형

jQuery는 같은 클래스의 요소를 루프합니다.

나는 반에 점쟁이가 많다testimonialjquery를 사용하여 특정 조건이 참인지 여부를 확인하기 위해 각 div를 루프합니다.그것이 사실일 경우 액션을 수행해야 합니다.

내가 이걸 어떻게 하는지 아는 사람?

각각 사용: 'i'는 배열의 위치입니다.obj반복하는 DOM 오브젝트입니다(jQuery 래퍼에서 액세스 가능).$(this)(도 마찬가지입니다).

$('.testimonial').each(function(i, obj) {
    //test
});

자세한 내용은 API 참조를 참조하십시오.

이거 먹어봐...

$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...


    if(condition){

    }


 });

요즘에는 jQuery 없이 이 작업을 수행하는 것이 매우 간단합니다.

jQuery 사용 안 함:

요소를 선택하고 메서드를 사용하여 반복하기만 하면 됩니다.

const elements = document.querySelectorAll('.testimonial');
Array.from(elements).forEach((element, index) => {
  // conditional logic here.. access element
});

이전 브라우저의 경우:

var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(element, index) {
  // conditional logic here.. access element
});

이 예시를 사용해 보세요.

HTML

<div class="testimonial" data-index="1">
    Testimonial 1
</div>
<div class="testimonial" data-index="2">
    Testimonial 2
</div>
<div class="testimonial" data-index="3">
    Testimonial 3
</div>
<div class="testimonial" data-index="4">
    Testimonial 4
</div>
<div class="testimonial" data-index="5">
    Testimonial 5
</div>

액세스 하고 싶은 경우divs가지고 있다data-index보다 크다2그럼 이 잡동사니

$('div[class="testimonial"]').each(function(index,item){
    if(parseInt($(item).data('index'))>2){
        $(item).html('Testimonial '+(index+1)+' by each loop');
    }
});

작업 예시 바이올린

이렇게 하면 된다

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});

jQuery의 .eq()를 사용하면 인덱스 접근 방식으로 요소를 통과할 수 있습니다.

var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
    var element = testimonialElements.eq(i);
    //do something with element
}
divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}

를 사용하여 간단하게 실행할 수 있습니다.다음 예제에서는 "something"이라는 단어를 포함하는 모든 .testimonal div를 숨깁니다.

$(".testimonial").filter(function() {
    return $(this).text().toLowerCase().indexOf("something") !== -1;
}).hide();

심플한 for 루프:

var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
  // Using $() to re-wrap the element.
  $(testimonials[i]).text('a');
}

질문의 일부를 놓치고 있는 것 같습니다만, 간단하게 이렇게 해 주실 수 있다고 생각합니다.

$('.testimonial').each((index, element) => {
    if (/* Condition */) {
        // Do Something
    }
});

여기에는 jQuery의 각 메서드가 사용됩니다.https://learn.jquery.com/using-jquery-core/iterating/

jQuery 업데이트 안 함

document.querySelectorAll('.testimonial').forEach(function (element, index) {
    element.innerHTML = 'Testimonial ' + (index + 1);
});
<div class="testimonial"></div>
<div class="testimonial"></div>

JavaScript ES6.forEach()에서는 다음과 같이 지정된 어레이와 같은 NodeList 컬렉션을 사용합니다.Element.querySelectorAll()

document.querySelectorAll(".testimonial").forEach((el, idx) => {
  el.style.color = "red";
  console.log(`${idx} Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );
});
<p class="testimonial" id="1">This is some text</p>
<div class="testimonial" id="2">Lorem ipsum</div>

$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});

jQuery $각 메서드를 사용하여 클래스 증언이 포함된 모든 요소를 루프할 수 있습니다.i = >는 컬렉션에 포함된 요소의 인덱스이며 val은 특정 요소의 객체를 제공합니다. "val"을 사용하여 요소의 속성에 더 접근하고 상태를 확인할 수 있습니다.

$.each($('.testimonal'), function(i, val) { 
    if(your condition){
       //your action
    }
});

정밀도 향상:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});

언급URL : https://stackoverflow.com/questions/4735342/jquery-to-loop-through-elements-with-the-same-class

반응형