开发者

jQuery, using .find on parent function?

I have the following jQuery script...

$(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)');
                }
            });
        }
    });
});

Its being run on the following code:

<div class="eventWrapper" data-service="livestream" data-serviceval="srklive">
 开发者_如何学JAVA   <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>

Its pretty self explanatory... it binds to the class .eventWrapper. When someone clicks anywhere in the div, it checks the data. If the data matches, it extracts a JSON query. This so far works perfectly fine.

The issue now is how to replace the text inside of the .eventTime class with what its supposed to. Obviously, I cant use $(this) because that relates to the existing getJSON function, not the bind function. How would I do this properly?

Also, how do I get the event to activate on page load, instead of on click?


store this as a variable to use within $.getJSON's callback so you're referring to the correct context/this

$(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)');
                }
            });
        }
    });
});


Would this work?

$('.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)');
            }
        });
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜