функция, которая обновляет цвет кнопки в зависимости от состояния потока сокращений

0

Мне интересно, может ли эта функция быть изменена для запуска при загрузке страницы, а не при нажатии кнопки (ов) с классом = "statusbutton"?

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$( document ).ready(function() {

    $( ".statusbutton" ).each(function(index){
        $(this).on("click", function(){
            var btnObj = this;

            $.getJSON( 'http://api.justin.tv/api/stream/list.json?channel=' + $(this).attr('id') + '&jsonp=?', function(twitchData) {

        if (typeof(twitchData[0]) !== 'undefined' && typeof(twitchData[0].stream_type) !== 'undefined') {
            if (twitchData[0].stream_type == 'live') {
                // live
                $(btnObj).css('background-color', '#00FF00');
            } else {
                // something other than live
                $(btnObj).css('background-color', '#f11');
            }
        }else{
            // no data or invalid data from twitch
            $(btnObj).css('background-color', '#f11');
        }



});

        });
    });
});

</script>
  • 0
    У вас есть вопрос? Я не понимаю, что вы спрашиваете.
  • 0
    там тема теперь отражает мою текущую проблему.
Теги:
button
function
onload

1 ответ

0
Лучший ответ

Предполагая, что ваши кнопки должны сохранять возможность запуска запроса AJAX при нажатии. Вы можете просто вручную запустить событие click на ваших .statusbutton кнопках сразу после DOM ready и после привязки обработчиков событий.

$(document).ready(function() {

    $(".statusbutton").each(function(index) {

        $(this).on("click", function() {
            var btnObj = this;
            $.getJSON('http://api.justin.tv/api/stream/list.json?channel=' + $(this).attr('id') + '&jsonp=?', function(twitchData) {
                if (typeof(twitchData[0]) !== 'undefined' && typeof(twitchData[0].stream_type) !== 'undefined') {
                    if (twitchData[0].stream_type == 'live') {
                        // live
                        $(btnObj).css('background-color', '#00FF00');
                    } else {
                        // something other than live
                        $(btnObj).css('background-color', '#f11');
                    }
                } else {
                    // no data or invalid data from twitch
                    $(btnObj).css('background-color', '#f11');
                }
            });
        });

    }).trigger('click'); // manually trigger 'click' to initiate AJAX request  

});
  • 0
    Ответ принят! Вы выиграли 1 миллион долларов!
  • 0
    офигенно, шучу, спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню