I'm trying to write a jQuery plugin that will provide additional functions/methods to the object that calls it.
(我正在尝试编写一个jQuery插件,它将为调用它的对象提供额外的函数/方法。)
All the tutorials I read online (have been browsing for the past 2 hours) include, at the most, how to add options, but not additional functions.(我在线阅读的所有教程(过去2小时内一直在浏览)包括最多如何添加选项,但不包括其他功能。)
Here's what I am looking to do:
(这是我要做的事情:)
//format div to be a message container by calling the plugin for that div
(//通过调用该div的插件将div格式化为消息容器)
$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");
or something along those lines.
(或类似的规定。)
Here's what it boils down to: I call the plugin, then I call a function associated with that plugin.(以下是它归结为:我调用插件,然后调用与该插件相关联的函数。)
I can't seem to find a way to do this, and I've seen many plugins do it before.(我似乎找不到办法做到这一点,我见过许多插件之前做过。)
Here's what I have so far for the plugin:
(这是我到目前为止的插件:)
jQuery.fn.messagePlugin = function() {
return this.each(function(){
alert(this);
});
//i tried to do this, but it does not seem to work
jQuery.fn.messagePlugin.saySomething = function(message){
$(this).html(message);
}
};
How can I achieve something like that?
(我怎样才能实现这样的目标?)
Thank you!
(谢谢!)
Update Nov 18, 2013: I've changed the correct answer to that of Hari's following comments and upvotes.
(2013年11月18日更新:我已经改变了Hari的评论和赞成的正确答案。)
ask by Yuval Karmi translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…