jQuery 在单击时调用自定义函数

jQuery call custom function on click

本文关键字:调用 自定义函数 单击 jQuery      更新时间:2023-09-26
单击

h1后,我将如何正确调用specialHouse函数,仍然允许$(this)表示div.content。目前,以下内容不适用于错误"未捕获的类型错误:对象 [对象对象] 没有方法'specialHouse'"

function specialHouse()
{
    $(this).slideDown(500, function(){
      $(this).delay(2000).slideUp();
    });
 };
$('div.content').hide();
$('h1').on('click', function(){
    $(this).next('div.content').specialHouse();
})

感谢您的任何帮助:)

你必须告诉jQuery你的新函数:

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

当我们返回this我们的函数是可链的:

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

你尝试它的方式仅适用于jQuery插件。但是,您可以像这样调用该函数(上下文this将按预期设置):

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

尝试:

$('div.content').hide();
$('h1').on('click', function(){
    specialHouse($(this).next('div.content'));
}) 
function specialHouse(elem){
  $(elem).slideDown(500, function(){
     $(this).delay(2000).slideUp();
   });
};