我正在尝试编写一个jQuery插件,它将为调用它的对象提供附加的函数/方法.我在线阅读的所有教程(过去2小时内一直在浏览)包括最多如何添加选项,但不包括其他功能.
这是我要做的事情:
//通过调用该div的插件将div格式化为消息容器
$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");
Run Code Online (Sandbox Code Playgroud)
或类似的规定.以下是它归结为:我调用插件,然后调用与该插件相关联的函数.我似乎找不到办法做到这一点,我见过许多插件之前做过.
这是我到目前为止插件的内容:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这样的目标?
谢谢!
2013年11月18日更新:我已经改变了Hari的评论和赞成的正确答案.
我试图用替换方法更改散列URL(document.location.hash),但它不起作用.
$(function(){
var anchor = document.location.hash;
//this returns me a string value like '#categories'
$('span').click(function(){
$(window).attr('url').replace(anchor,'#food');
//try to change current url.hash '#categories'
//with another string, I stucked here.
});
});
Run Code Online (Sandbox Code Playgroud)
我不想更改/刷新页面,我只想更换URL而不做任何回复.
注意:我不想用href ="#food"解决方案来解决这个问题.
我可能会犯一个非常简单的错误,但是我有一些严重的麻烦,要弄清楚为什么它不起作用.
这是代码:http://jsfiddle.net/HthCa/
更新:这是我的实际代码..
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript">
$(function() {
$('#test').customTabs();
})
</script>
Run Code Online (Sandbox Code Playgroud)
scripts.js中
$.fn.customTabs = function() {
alert($(this).html());
}
Run Code Online (Sandbox Code Playgroud)