简体   繁体   中英

jQuery: Call a function twice

I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:

$('div').each(function truncate() {
    $(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});

$('.truncate').click(function() {

    if ($(this).parent().hasClass('closed')) {
        $(this).parent().removeClass('closed').addClass('open').children().show();
    }

    else if ($(this).parent().hasClass('open')) {
        $(this).parent().removeClass('open').addClass('closed');
        $('div').truncate();
        $(this).show();
    }

});

The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?

Edit jsFiddle here: http://jsfiddle.net/g6PLu/

That's a named function literal.

The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.

Instead, create a normal function and pass it to each() :

function truncate() { ...}

$('div').each(truncate);

What's the error message do you get?

You should create function and then call it as per requirement

Define the function

function truncate(){
  $('div').each(function(){

  });
}

Then call the function

truncate();

Another approach is to establish, then trigger, a custom event :

$('div').on('truncate', function() {
    $(this).......;
}).trigger('truncate');

Then, wherever else you need the same action, trigger the event again.

To truncate all divs :

$('div').trigger('truncate');

Similarly you can truncate just one particular div :

$('div#myDiv').trigger('truncate');

The only prerequisite is that the custom event handler has been attached, so ...

$('p').trigger('truncate');

would do nothing because a truncate handler has not been established for p elements.

I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate ). And makes for much cleaner code

(function($) {
    $.fn.truncate = function() {
        this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
    };
    $.fn.untruncate = function() {
        this.removeClass('closed').children().show();
    };                
})(jQuery);

$('div').truncate();

$('.truncate').click(function() {
  var $parent = $(this).parent();
  if ($parent.hasClass('closed')) {
    $parent.untruncate();
  } else {
    $parent.truncate();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM