jquery在自定义函数中使用(this)

jquery using (this) in custom function

本文关键字:this 自定义函数 jquery      更新时间:2023-09-26

我创建了一个小的jquery脚本,在自定义函数中使用(this)时遇到了问题。

这是代码:

jQuery("li").click(function()
{
    var scrollTop = jQuery(window).scrollTop();
    if(scrollTop > 0)
    {
        jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function()
        {
            fadeItems();
        });
    }
    else
    {
        fadeItems();    
    }
});
function fadeItems()
{       
    var slogan = jQuery(this).children('p').html();
    jQuery('#slogan_text').fadeOut(150, function(){
        jQuery('#slogan_text').fadeIn(150).html(slogan);
    });
    var content = jQuery(this).children('#post_content_large').html();
    jQuery('#content_view').html(content).hide();
    var status = jQuery("#readMore").html();
    if(status == 'Verbergen')
    {
        jQuery('#content_view').fadeIn(500, function(){
            jQuery('#content_view').fadeIn(500).html(content);
        });
    }
    var title = jQuery(this).children('h3').html();
    jQuery('#title_content').fadeOut(150, function(){
        jQuery('#title_content').fadeIn(150).html(title);
    });
}

因此,该函数在单击列表项时运行,并且会很好,但是(this)的值为空

有人知道如何解决这个问题吗?

提前感谢!

.call在这里很有用:

jQuery("li").click(function () {
    var self = this;
    var scrollTop = jQuery(window).scrollTop();
    if(scrollTop > 0) {
        jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function() {
            fadeItems.call(self);
        });    
    }
    else {
        fadeItems.call(self);
    }    
});

因为您必须将其传递给函数才能使用它(也可能使用与此不同的圆顶,不那么令人困惑(编辑,因为您想要单击的项目)

    var clicked = this;
    jQuery('html, body').animate( { scrollTop: 0 }, 'slow', function()
    {
        fadeItems(clicked);
    });
function fadeItems(el)
{       
var slogan = jQuery(el).children('p').html();

使用应用:

fadeItems.apply(this);

这样您就可以指定函数调用的上下文(手动分配 this 的值 fadeItems

编辑:如@KevinB所述,您需要在父函数中为this别名:var that = this;,然后将that传递到函数中,fadeItems.apply(that);