这是我的实际代码:
$.fn.menuWidth = (function(){
return {
show: function(a){
this.animate({
width: 400
});
},
hide: function(a){
return "hide";
}
};
}());
$("#header").menuWidth.show();
但是,我无法从显示对象
访问$("#header")
。知道如何让它发挥作用吗?
最佳答案
您可能希望将插件定义的结构更改为如下所示
$.fn.menuWidth = function(options) {
this.show = function() {
this.animate({
width: 400
});
return this; // <---- This will enable chaining
};
this.hide = function() {
return "hide";
};
return this; // <--- returning this will make visible the hide and show methods.
};
console.log($("#header").menuWidth().show().hide());
执行 jQuery 的显示和隐藏也是可能的,但这可能听起来有点像黑客。
$($("#header").menuWidth().show()).hide();
menuWidth 插件返回 this
这是元素的实例。将其包装到 jQuery 对象中将使我们执行 .hide()
和 .show()
。
如果调用menuWidth的.hide()
,则这是不可能的,因为它不返回元素实例。
PS:这是一种非常非常简单的插件编写方法。有更好、更复杂的方法来编写插件。
$.fn.menuWidth = function(options) {
this.show = function() {
this.animate({
width: 400
});
return this;
};
this.hide = function() {
return "hide";
};
return this;
};
console.log($("#header").menuWidth().show().hide());
#header{
width: 100px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
This is a header
</div>
关于javascript - 来自 JavaScript 模式的 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31391513/