2014-06-04 3 views
0

img 태그에서 'size-'로 시작하는 특정 클래스 이름을 가져 오려고 시도하고 전체 클래스 이름을 변수로 저장 한 다음 addClass()를 사용하여 변수를 전달합니다. img 부모에게 .wp-caption div.jquery 변수를 사용하여 요소에 클래스 추가

HTML

<div id="attachment_101" style="width: 470px" class="wp-caption alignleft"> 
    <img class="wp-image-101 size-medium" src="http://192.168.0.8/wp-content/uploads/2014/06/01picAC-460x345.jpg" alt="01picAC" width="460" height="345"> 
    <p class="wp-caption-text">Even though 3-D graphics have been used in the Repair Manual and New Car Features, the 3-D graphics had not been used for technical training.</p> 
</div> 

jQuery를

$('.post img').each(function() { 
    var imgSize = this.className.match(/\bsize-[^\s]+\b/); 
    $(this).parent('.wp-caption').addClass(imgSize); 
}); 

내 문제는 변수 imgSize 클래스로 추가되지 않을 것입니다.

$('.post img').each(function() { 
    var imgSize = this.className.match(/\bsize-[^\s]+\b/); 
    $(this).parent('.wp-caption').attr('class', imgSize); 
}); 

을 ...하지만 필요한 기존 .. 정렬 클래스를 제거합니다

나는 작업 할 수 있습니다.

.wp-caption div에 대한 클래스에 'size- [whatever]'변수를 추가하는 방법을 알아야합니다.

제발 도와주세요 - 나는 이것을 알아 내려고 한 시간 동안 벽에 머리를 두드 리고있었습니다.

+1

* 힌트 :'을 console.log (imgSize)' – adeneo

+0

hint2을 반환! 0을 추가하는 것이 무슨 뜻인지 말해 줄 수 있습니까? 슈퍼 빠른 응답 주셔서 감사합니다. – Spoeken

답변

0

시도 :

$('.post img').each(function() { 
    var imgSize = this.className.match(/\bsize-[^\s]+\b/)[0]; 
    $(this).parent('.wp-caption').addClass(imgSize); 
}); 
+0

작품 : *'regex.match()가'배열 – samhadr

+0

var'imgSize'는 @adeneo가 가리키는 배열입니다. 마지막에'[0]'은 배열의 첫 번째 문자열을 얻는 것입니다. – Spoeken

+0

알았습니다. 고마워요! – samhadr

관련 문제