2013-10-09 2 views
0

에서 여러 이미지를 이미지 크기를 감지 나는이 jQuery를 가지고 :JQuery와 DIV

jQuery(".storyImg").each(
function(){ 
    if(this.width() > this.height()){ 
     jQuery(this).addClass("landscape"); 
    } else if (this.width() < this.height()){ 
     jQuery(this).addClass("portrait"); 
    } else { 

    } 
} 
); 

그것은 작동하지 않는 것 같습니다. 나는 심지어 그 기능 안에서 경고를 발령 할 수 없다. 그것은 확실히 html 파일에 포함되어 있으며 .storyImg 클래스는 확실히 정확합니다.

+0

jQuery가로드되지 않았거나 페이지 맨 아래로 이동해야합니다. –

답변

1

, 당신은 요소에 대한 jQuery를 래퍼 그 메소드를 호출 할 필요가

jQuery(".storyImg").each(function() { 
    var $this = jQuery(this) 
    if ($this.width() > $this.height()) { 
     $this.addClass("landscape"); 
    } else if ($this.width() < $this.height()) { 
     $this.addClass("portrait"); 
    } else { 

    } 
}); 
0

this은 jQuery 객체가 아니기 때문에 jQuery(this).width()jQuery(this).height()을 사용해야합니다. 콘솔에 오류가 산재 해 있어야합니다. this에서 jQuery를 한 번 호출하면됩니다.

$(window).load()에서 이미지를로드 할 때까지 기다려야하므로 기다려야합니다. thiswidth 또는 height 방법이없는 DOM 요소를 의미 each 콜백 내부

jQuery(".storyImg").each(function(){ 
    var $this = jQuery(this); 
    if($this.width() > $this.height()){ 
    $this.addClass("landscape"); 
    } else if ($this.width() < $this.height()){ 
    $this.addClass("portrait"); 
    } else { 

    } 
}); 
0

없는 JS 전문가 만 당신은 this.width() 전화를 할 수 없습니다. 이미 당신처럼 거기에 jQuery(this).width()을 사용했을 것입니다. 여전히 var에 추가하는 것이 더 좋습니다.

var $this = jQuery(this); 
if($this.width() > $this.height()){ 
    // blah 
}