-1

나는 이런 식으로 해결해야 할 상황에 처해있다. local variableglobal variable으로 변환해야합니다. this answer.에서이 메서드를 찾은 이미지의 실제 너비와 높이를 반환하는 예제가 있습니다.jQuery : 외부 변수에 액세스하는 방법?

국부 변수 pic_real_heightpic_real_width을 전역 변수로 변환해야합니다. 실제 값을 반환해야합니다.

Here is jsFiddle.

CSS :

img { width:0px; height:0px; }​ 

jQuery를 :

console.log($('.imgCon img').height());//returns 0 

var img = $('.imgCon img')[0]; // Get my img elem 
var pic_real_width, pic_real_height; 
$('<img/>').attr('src', $(img).attr('src')).load(function() { 
     pic_real_width = this.width; 
     pic_real_height = this.height; 

     console.log(pic_real_width + 'x' + pic_real_height); 
     // -- returns true 570x320 -- 
}); 
//problem starts here: 
console.log(pic_real_width + 'x' + pic_real_height); 
//returns undefined 
// need to return this as an global variable 570x320 
+6

그들은 이미 세계하지만 부하가 비동기 발생합니다. 콜백 함수에서 알림 이동하기 – Bergi

+0

주로 Chrome, Firefox (Firebug 포함) 또는 IE9에서 테스트하여'alert()'대신'console.log()'를 사용하는 법을 배우십시오. –

+2

@Bergi가 말했듯이, * 콜백 *은 호출 된'$ .load()'('function' 부분을보십시오)에 의해 호출되며, 문자 그대로 이것은 * 나중에 발생합니다 *. 콜백이 어떻게 작동 하는지를 알아야합니다. –

답변

2

이 줄,

console.log(pic_real_width + 'x' + pic_real_height);

,이 라인

pic_real_width = this.width; 
    pic_real_height = this.height; 

    console.log(pic_real_width + 'x' + pic_real_height); 
    // -- returns true 570x320 -- 

실행 대기의 비동기 때문에하지 않습니다. 콜백 함수가 호출되기 전에

따라서 console.log(pic_real_width + 'x' + pic_real_height);를 실행한다 (즉, 사용자는 widthheight을 설정하기 전에).

이미 정의 했으므로 undefined으로 표시됩니다.

일반의 솔루션이 될 것이다,

$('<img/>').attr('src', $(img).attr('src')).load(function() { 
     pic_real_width = this.width; 
     pic_real_height = this.height; 

     console.log(pic_real_width + 'x' + pic_real_height); 
     // -- returns true 570x320 -- 
     restOfMyProcessing(); 

}); 

function restOfMyProcessing() { 
    console.log(pic_real_width + 'x' + pic_real_height); 
} 
+0

그것의 일은 고마운 친구 http://jsfiddle.net/mjaA3/79/ –

+0

환영합니다. 그러나 js의 비동기 특성과 관련된 콜백에 대해 읽어보십시오. 어느 날 아약스 콜을 할 것입니다. – Jashwant

+0

나는 다시 배우려고 노력하고있다. 다시 한번 감사한다. –

0

당신은 이미지로드 이벤트에 설정하기 전에 pic_real_width 및 pic_real_height를 사용하려고합니다.
코드에서와 마찬가지로 먼저 alert(pic_real_width + 'x' + pic_real_height)은 이미지로드 함수 중 하나이며 undefined을 반환하고로드 이벤트의 두 번째 alert은 예상 한 값을 반환합니다.
가로드 기능/이벤트 후 소스 속성의 설정을 이동하는 것이 좋습니다 있지만 :

$('<img/>') 
.load(function() { 
    pic_real_width = this.width; 
    pic_real_height = this.height; 

    alert(pic_real_width + 'x' + pic_real_height); 
    // -- returns true 570x320 -- 
    //now continue process here or call another function... 
}) 
.attr('src', $(img).attr('src')); 
관련 문제