jQuery如何在原型中调用方法
jQuery how to call a method within a prototype?
jQuery:
function Morphing( button, container, content) {
this.button = button;
this.container = container;
this.content = content;
this.overlay = $('div.overlay');
}
Morphing.prototype.startMorph = function() {
this.button.on('click', function() {
$(this).fadeOut(200);
Morphing.containerMove();
// Work on from here!
// setTimeout(Morphing.containerMove, 200);
});
};
Morphing.prototype.containerMove = function() {
console.log(this);
this.overlay.fadeIn();
this.container.addClass('active');
this.container.animate(Morphing.endPosition, 400, function() {
this.content.fadeIn();
this.span.fadeIn();
Morphing.close();
});
};
当点击按钮时,我试图运行containerMove函数,但我收到了错误:
[Error] TypeError: undefined is not a function (evaluating 'Morphing.containerMove()')
(anonymous function) (newScript.js, line 11)
dispatch (jquery.min.js, line 3)
i (jquery.min.js, line 3)
这是唯一的错误。我想这是因为我错误地调用了该方法?谢谢
顺便说一句:原型中的写作方法是否像我所做的那样是一个很好的练习?
额外代码:
忘了提,这是在我的index.html:
<script>
$(document).ready(function() {
var morph = new Morphing( $('button.morphButton'), $('div.morphContainer'), $('h1.content, p.content') );
morph.startMorph();
});
</script>
最简单的方法是将原始this
存储在闭包中
Morphing.prototype.startMorph = function() {
var me = this;
this.button.on('click', function() {
$(this).fadeOut(200);
me.containerMove();
// Now for the set timeout, you'll want to make sure it's
// called with the corect `this`, You can use Function.bind
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
setTimeout(me.containerMove.bind(me), 200);
});
};
在事件处理程序中,this
指向元素本身,正如您从调用$(this).fadeOut(200);
但需要访问处理程序之外的this
这一事实中所理解的那样。
相关文章:
- 未捕获错误:无法在初始化之前调用方法;
- 通过ajax从客户端调用C#方法来执行C#方法
- 如何避免在angular上多次调用方法;s ng重复
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 从window.onbeforeunload调用方法背后的代码
- 当输入字段为空时,如何在angular中调用方法
- 函数调用方法有什么用
- 多次调用方法后返回相同promise的模式
- 当从Chrome扩展动态注入JS时,从onload()内部调用方法
- 茉莉花 - 未调用方法
- jQuery如何在原型中调用方法
- ng显示“;调用方法“;不起作用
- Odoo销售点如何访问模型并使用JS调用方法
- 从React调用方法.JS州
- TinyMCE验证给出错误:无法调用方法'getContent'的未定义
- 向模板实例变量传递调用方法调用的结果时出现异常
- 如何在对象中调用方法
- 检查对话框是否为 Open 会引发“初始化前无法在对话框上调用方法”错误
- 在输入类型提交按钮上调用 C# 方法
- 通过类选择器单独调用方法