简体   繁体   中英

jQuery call custom function on click

How would I correctly call the specialHouse function after the h1 was clicked, in way that would still allow $(this) to represent div.content. Currently the below does not work with the error "Uncaught TypeError: Object [object Object] has no method 'specialHouse'"

function specialHouse()
{
    $(this).slideDown(500, function(){
      $(this).delay(2000).slideUp();
    });
 };

$('div.content').hide();
$('h1').on('click', function(){
    $(this).next('div.content').specialHouse();
})

Thanks for any help :)

You have to tell jQuery about your new function:

jQuery.fn.specialHouse = function() {
   return this.slideDown(500, function(){
     $(this).delay(2000).slideUp();
   }
}

As we return this our function is chain able:

$("a").specialHouse().text("Hello World");

The way you've tried it works only for jQuery plugins. You can however invoke the function like this (the context this will be set as expected):

$('h1').on('click', function() {
    $(this).next('div.content').each(specialHouse);
});

Try :

$('div.content').hide();
$('h1').on('click', function(){
    specialHouse($(this).next('div.content'));
}) 

function specialHouse(elem){
  $(elem).slideDown(500, function(){
     $(this).delay(2000).slideUp();
   });
};

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