2010-08-26 2 views
0

В принципе, когда я нажимаю кнопку, я хочу, чтобы вызвать функцию и запустить функцию кнопки CLICK:JQuery - Нажмите функцию вызова и нажмите функцию

Эта JQuery работает при загрузке страницы:

jQuery(document).ready(function ($) { 
    $('ul li:first-child').addClass('first_item'); 
    className = $('.first_item').attr('id'); 
    alert('Date is:'+ className +'.'); 
}); 

И это JQuery работает, когда кнопка нажата:

jQuery(document).ready(function ($) { 
    $('.button').click(function() { 
     $('.tweets ul').prepend($('.refreshMe').html()); 
    }); 
}); 

Я хочу сделать как при нажатии на кнопку, как я могу объединить два?

PP:

Что делать, если я хотел бы добавить еще одну функцию в смесь, все сбегаются:

$(".refreshMe").everyTime(5000,function(i){ 
     $.ajax({ 
      url: "test.php?latest="+className+"", 
      cache: false, 
      success: function(html){ 
      $(".refreshMe").html(html); 
      } 
     }) 
    }) 

ответ

2

Поместите код, работающий на странице загрузки в функции, которая вызывается в обоих ситуации.

// Place all the code in one .ready() function instead of two. 
jQuery(document).ready(function ($) { 

     // Place your code in its own function 
    function initialize() { 
     $('ul li:first-child').addClass('first_item'); 
     className = $('.first_item').attr('id'); 
     alert('Date is:'+ className +'.'); 
    } 

     // Call the function on page load 
    initialize(); 

    $('.button').click(function() { 
     $('.tweets ul').prepend($('.refreshMe').html()); 
      // Call the function in the click handler 
     initialize(); 
    }); 
}); 
0

Используйте отдельную функцию, например:

function doThings() { 
    $('ul li:first-child').addClass('first_item'); 
    className = $('.first_item').attr('id'); 
    alert('Date is:'+ className +'.'); 
} 

$(document).ready(function() { 
    doThings(); 
    $('.button').click(function() { 
     $('.tweets ul').prepend($('.refreshMe').html()); 
     doThings(); 
    }); 
}); 
Смежные вопросы