2014-09-03 2 views
1

클래스 이름이 "div"이고 클래스 이름이 다른 div (예 : 런던, 글래스고 등) 목록이 있습니다.클래스 이름을 사용하여 같은 이름의 변수를 호출하십시오.

함수에서 두 번째 클래스 이름을 변수로 사용하려고합니다. 나는 숫자를 나타내는 변수에 반대 단지 문자열로 읽는 기능 ...에 두 번째 클래스 이름을 에코 경우 현재이 공식은 숫자로 단어를 사용하는 것을 시도하고 반환

var resize = function() { 
    $('.dot').each(function() { 
     uniName = $(this).attr('class').split(' ')[1]; 
     uniNameMargin = uniName/2 - uniName; 
     $('.' + uniName).animate({ 
      width: uniName, 
      height: uniName, 
      marginLeft: uniNameMargin, 
      marginBottom: uniNameMargin 
     }, 300); 
    }); 

숫자와 반대로 많은 NaNs

대신 관련 변수로 읽는 방법이 있습니까?

감사합니다.

+0

변수를'String()'으로 묶어보세요. – Newtt

+1

'parseInt (val, 10)'을 사용해야합니다. –

+0

'uniNameMargin = + uniName/2 - uniName; '과 같은 정수로 변환하려면'+'를 추가하십시오. –

답변

2

이러한 변수가 어디에 정의되어 있는지 표시하지 않지만 전역 변수라고 가정합니다. 그렇다면, 그것들은 웹 브라우저에서 window 속성 인 전역 객체의 속성이기도합니다.

당신은 문자열로 객체의 속성 이름이있는 경우, 대괄호 표기법을 사용하여 해당 속성에 액세스 할 수 있습니다 : 가정, 내가 말한 그래서, (이처럼 변수의 값에 액세스 할 수 있습니다

var my_object; 
my_object.london = 1; 

var property_name = "london"; 
console.log(my_object[property_name]); // Will log 1 to the console 

을 그들은) 전역 변수를 위치 :

uniName = $(this).attr('class').split(' ')[1]; // After this line, I’m assuming uniName has a value like "london" 
    var uniNumber = window[uniName]; 
    uniNameMargin = uniNumber/2 - uniNumber; // Here, we use [] notation to access the "london" property of the window object. If you have a global variable called "london" with a numerical value, this should now work. 

나는 또한 $('.dot').each 함수에서 변수는 함수가를 사용하여 내에서 선언되지 않은 것을 알 수. 이러한 변수가 이미 더 높은 범위에서 선언 된 경우에는 멋지지만 해당 함수에서만 사용되는 경우 var 키워드를 사용하여 해당 함수에서 선언해야하므로 부모 또는 전역 범위를 오염시키지 않아야합니다. 필요하지 않은 변수 :

$('.dot').each(function() { 
    var uniName = $(this).attr('class').split(' ')[1]; 

    var uniNumber = window[uniName]; 

    var uniNameMargin = uniNumber/2 - uniNumber; 

    $('.' + uniName).animate({ 
     width: uniName, 
     height: uniName, 
     marginLeft: uniNameMargin, 
     marginBottom: uniNameMargin 
    }, 300); 
}); 
+2

'window [uniName]/2 - window [uniName]; ' – noamtcohen

+0

@noam : 예, 맞습니다. 고맙습니다. –

+1

환상적. 훌륭한 작품, 설명 주셔서 감사합니다! – bboybeatle

관련 문제