2012-03-30 2 views
2

배열을 채우는 html 이미지 태그가 몇 개 있습니다. 페이지 - http://www.digitalbrent.com/lab - 배열의 세 요소가 표시됩니다. 단추를 클릭 한 후에 클래스를 추가해야합니다. img가 배열에서 표시되면 클래스는 각각 다릅니다. . 여기에 코드입니다 :배열의 html 요소에 Jquery .addClass 사용

$(document).ready(function(){  //populates array with images 

    var shipImgs = $("#thumb_slider").children(); 
    console.log(shipImgs); 

    $.each(shipImgs,function(i,elem){ 
     var tag = "<img src='" + $(elem).attr('src') + "' alt='space'/>"; // This is how I made the image tags. 
     imgArr.push(tag); 
    }); 
    console.log(imgArr); 

}); 

$("#basic_ul").html(imgArr[b] + imgArr[a] + imgArr[c]); //displays the images 
     imgArr[b].addClass("left_slot"); 
     imgArr[a].addClass("middle_slot"); 
     imgArr[c].addClass("right_slot"); 

나는 또한 배열 항목 주위의 선택, $ (imgArr [B]) addClass ("left_slot")와 함께 시도했다가; 그러나 그것도 작동하지 않았다.

전혀 조언을 크게 주시면 감사하겠습니다. 나는 stackoverflow에 비슷한 질문을했지만 행운을 봤어. 나는이 프로젝트를 잠시 동안 연구 해왔고 아무 것도 찾을 수 없다.

+0

죄송 배열을보기 위해 페이지에서 찾고 있다면, 당신은 증가 버튼을 눌러야 할 수 있습니다 –

답변

4

만 이미지 태그 'HTML의 문자열 배열을 보유하고 있습니다.

대신 jQuery 함수에 해당 문자열을 전달하면 문서에 추가 할 수있는 메모리 내 노드가 생깁니다.

가 위의 코드를 변경해보십시오 : 당신은 문자열로 .addClass하려고하는

$(document).ready(function(){  //populates array with images 
    var $basicUl = $('#basic_ul'); // cache the selector 
    var shipImgs = $("#thumb_slider").children().each(function(index, element) { 
     var newImg = $("<img />").attr({src: this.src, alt: 'space'}).addClass(index == 0 ? "middle_slot" : (index == 1 ? "left_slot" : "right_slot")); 
     $basicUl.append(newImg); 
    }); 
}); 
+0

감사합니다. 완벽하게 작동합니다! –

+0

@DigitalBrent 아니 probs! 제 코드의 어떤 부분이 불분명합니까? HTML 문자열과 실제 DOM 요소 사이의 중요한 차이, 특히 jQuery와 관련된 중요한 점을 이해하고 있습니까? 내가 더 명확하게 말할 수 있는지 알려줘. – GregL

1

이 아니라 each()을 사용해야 jQuery 콜렉션을 반복 할 수 있습니다. 귀하의 imgArr

shipImgs.each(function() { 
    var img = "<img src='" + $(this).attr('src') + "' alt='space'/>"; 
    imgArr.push(img); 
}); 
+0

그래서이 문서는 http://api.jquery.com 말씀 :이 같은 시도 /jQuery.each/ – tusar

1

-imgArr[b]이 문자열이 아닌 요소, 당신은 문자열로 클래스를 추가 할 수 없습니다.

$(document).ready(function(){  //populates array with images 

    var shipImgs = $("#thumb_slider").children(); 
    console.log(shipImgs); 

    $.each(shipImgs,function(i,elem){ 
     var tag = $("<img src='" + $(elem).attr('src') + "' alt='space'/>"); // This is how I made the image tags. 
     imgArr.push(tag); 
    }); 
    console.log(imgArr); 

}); 

$("#basic_ul").append(imgArr[b]); 
$("#basic_ul").append(imgArr[a]); 
$("#basic_ul").append(imgArr[c]); 
imgArr[b].addClass("left_slot"); 
imgArr[a].addClass("middle_slot"); 
imgArr[c].addClass("right_slot");