나는 이런 식으로 해결해야 할 상황에 처해있다. local variable
을 global variable
으로 변환해야합니다. this answer.에서이 메서드를 찾은 이미지의 실제 너비와 높이를 반환하는 예제가 있습니다.jQuery : 외부 변수에 액세스하는 방법?
국부 변수 pic_real_height
및 pic_real_width
을 전역 변수로 변환해야합니다. 실제 값을 반환해야합니다.
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
그들은 이미 세계하지만 부하가 비동기 발생합니다. 콜백 함수에서 알림 이동하기 – Bergi
주로 Chrome, Firefox (Firebug 포함) 또는 IE9에서 테스트하여'alert()'대신'console.log()'를 사용하는 법을 배우십시오. –
@Bergi가 말했듯이, * 콜백 *은 호출 된'$ .load()'('function' 부분을보십시오)에 의해 호출되며, 문자 그대로 이것은 * 나중에 발생합니다 *. 콜백이 어떻게 작동 하는지를 알아야합니다. –