开发者

jQuery - Click call function and click function

Basically when I click a button I want to call a function and run the button click function:

This jQuery runs when the page loads:

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

And this jQuery runs when the a button is clicked:

jQuery( document ).ready( function ( $ ) {
    $('.button').click(f开发者_如何学Pythonunction() {
        $('.tweets ul').prepend($('.refreshMe').html());
    });
});

I want to do both when the button is clicked, how can i combine the two?

P.P:

What If i wanted to add another function into the mix, all to run together:

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


Place the code that runs on page load in a function that is called in both situations.

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


Use a separate function, like this:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜