jquery在自定义函数中使用(this)
jquery using (this) in custom function
我创建了一个小的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);
。
相关文章:
- 自定义函数中的光标位置
- Google Sheet自定义函数返回0
- 其中是自定义函数中的属性
- 创建自定义函数以在函数上运行完整的多选下拉列表
- Google Sheets自定义函数条件格式
- dalek回调或自定义函数
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 评估作为参数传递给 Google 电子表格中自定义函数的条件
- 具有自定义函数调用的 HTML 表单
- 使用 jQuery 对动态创建的元素调用自定义函数
- 从自定义函数返回promise
- extjs-使用传递的参数创建自定义函数
- AngularJS DI用于自定义函数
- Javascript 自定义函数错误
- 如何使用Angular 1.5组件将属性求值为字符串,这是一个自定义函数
- 为谷歌工作表创建一个自定义函数
- Angular2 在创建 ngSwitch 新视图后调用自定义函数
- JavaScript自定义函数返回意外值
- jquery在自定义函数中使用(this)
- jQuery自定义函数- this.each