2011-09-03 3 views
0

나는 다음과 같은 jQuery를 스크립트를 가지고 ... 다음 코드에서 실행중인jQuery, 부모 함수에서 .find 사용?

$(function() { 
    $('.eventWrapper').bind('click', function(event) { 

     var srvName = $(this).data('service'); 
     var srvVal1 = $(this).data('serviceval'); 

     if (srvName == 'livestream') 
     { 
      var query = 'http://x'+srvVal1+'x.api.channel.livestream.com/2.0/livestatus.json?callback=?'; 
      $.getJSON(query, function(data) 
      { 
       if (data['channel']['isLive']) 
       { 
        $(this).find('.eventTime').html('<b>Currently Live</b> ('+data['channel']['currentViewerCount']+' viewers)'); 
       } 
      }); 
     } 
    }); 
}); 

그것 :

<div class="eventWrapper" data-service="livestream" data-serviceval="srklive"> 
    <div class="eventIcon"><a href=""><img src="image.php?u=3942"></a></div> 
    <div class="eventName"><a href="">This is a test!</a></div> 
    <div class="eventTime">09-02-2011 08:00 PM</div> 
</div> 

그것의 꽤 자기 설명은 ... 그것은 클래스 .eventWrapper에 결합한다. 누군가 div의 아무 곳이나 클릭하면 데이터를 검사합니다. 데이터가 일치하면 JSON 쿼리가 추출됩니다. 이것은 지금까지 완벽하게 잘 작동합니다.

이제 문제는 .eventTime 클래스 내부의 텍스트를 원래대로 바꾸는 방법입니다. 분명히, 나는 bind() 함수가 아니라 기존의 getJSON 함수와 관련이 있기 때문에 $ (this)를 사용할 수 없다. 어떻게하면 제대로 할 수 있을까요?

또한 클릭 할 때 대신 페이지로드시 활성화 할 이벤트를 얻으려면 어떻게해야합니까? 올바른 컨텍스트를 참조하고, 그래서 $ .getJSON 콜백 내에서 사용할 수있는 변수로

답변

2

저장이 /이

$(function() { 
    $('.eventWrapper').bind('click', function(event) { 
     var $this = $(this); 
     var srvName = $(this).data('service'); 
     var srvVal1 = $(this).data('serviceval'); 

     if (srvName == 'livestream') 
     { 
      var query = 'http://x'+srvVal1+'x.api.channel.livestream.com/2.0/livestatus.json?callback=?'; 
      $.getJSON(query, function(data) 
      { 
       if (data['channel']['isLive']) 
       { 
        $this.find('.eventTime').html('<b>Currently Live</b> ('+data['channel']['currentViewerCount']+' viewers)'); 
       } 
      }); 
     } 
    }); 
}); 
+0

감사합니다. 이제이 스크립트를 클릭 대신 페이지로드에서 실행하려면 어떻게해야합니까? –

+0

나는 당신의 말씨가 약간 벗어난 것 같아요. 나는''.''this''를'$ .getJSON'의 콜백 내에서 사용할 변수로 저장합니다. 올바른 컨텍스트 /'this' (또는 그 효과가있는 것)를 참조하고 있습니다. 그러나 +1, spot on. – karim79

+0

@ karim79 : 죄송합니다, 원어민이 아니 십니다 편집 됨 – genesis

1

겠습니까이 작품?

$('.eventWrapper').bind('click', function(event) { 

    var srvName = $(this).data('service'); 
    var srvVal1 = $(this).data('serviceval'); 
    var evtTime = $(this).find('.eventTime'); 

    if (srvName == 'livestream') 
    { 
     var query = 'http://x'+srvVal1+'x.api.channel.livestream.com/2.0/livestatus.json?callback=?'; 
     $.getJSON(query, function(data) 
     { 
      if (data['channel']['isLive']) 
      { 
       evtTime.html('<b>Currently Live</b> ('+data['channel']['currentViewerCount']+' viewers)'); 
      } 
     }); 
    } 
});