2013-09-06 8 views
1

정상적으로 수정할 수없는 일부 템플릿 코드에서 '해킹'하는 코드 스 니펫이 있습니다. 내가 콘솔에서 다음과 같은 오류를 받고 있어요 브라우저에서 발사 이상이 스크립트시Jquery : TypeError : 텍스트가 정의되지 않았습니다.

<script> 
jQuery(document).ready(function() { 
    jQuery(".avatar").each(function() { 
     var text = jQuery(this).attr("src"); 
     text = text.replace("-64x64.jpg", ".jpg"); 
     text = text.replace("-80x80.jpg", ".jpg"); 
     text = text.replace("-32x32.jpg", ".jpg"); 
     text = text.replace("-28x28.jpg", ".jpg"); 
     text = text.replace("-16x16.jpg", ".jpg"); 
     text = text.replace("-128x128.jpg", ".jpg"); 
     jQuery(this).attr("src", text); 
    }); 
}); 
</script> 

:

TypeError: text is undefined 
text = text.replace("-64x64.jpg", ".jpg"); 

내 머리를 건 드리는하지만 아무것도오고. var 텍스트를 사용해 보았습니다. 시도하고 스크립트의 시작 부분에 그것을 정의하고 아무것도하지 않았 뭔가 모두와 충돌하는 경우 다른 변수 이름을 사용하여 시도 ....

+1

html을 제공 할 수 있습니까? – tliokos

답변

7

이것은 클래스의 요소 중 적어도 하나를 의미합니다 avatar에는 src 특성이 없습니다. attr은 문제의 요소에 특성이 전혀없는 경우 undefined을 반환합니다.

가드를 넣을 수 있습니다 (if (text)). 여기에 예제가 있습니다. 또한 jQuery(this).attr("src")을 사용할 이유가 없습니다. 단지 this.src 사용 : 각에서 어떤 자리에 대한 특정하지 않고,

jQuery(document).ready(function() { 
    jQuery(".avatar").each(function() { 
     if (this.src) { 
      this.src = this.src.replace(/-(\d+x\d+)\.jpg$/, ".jpg"); 
     } 
    }); 
}); 

.jpg으로 -DIGITSxDIGITS.jpg를 대체합니다 :

jQuery(document).ready(function() { 
    jQuery(".avatar").each(function() { 
     if (this.src) { 
      this.src = this.src.replace("-64x64.jpg", ".jpg") 
          .replace("-80x80.jpg", ".jpg") 
          .replace("-32x32.jpg", ".jpg") 
          .replace("-28x28.jpg", ".jpg") 
          .replace("-16x16.jpg", ".jpg") 
          .replace("-128x128.jpg", ".jpg"); 
     } 
    }); 
}); 

당신은 또한 아마 정규 표현식을 사용하여 좀 더 강력한 그 코드를 만들 수 있습니다 케이스가 있습니다. \d은 "임의의 숫자"를 의미하고 "012"는 "하나 이상"을 의미 한 후에 +을 의미합니다.

+0

완벽한 솔루션. 감사! –

관련 문제