javascript - 来自 JavaScript 模式的 jQuery 插件

标签 javascript jquery

这是我的实际代码:

$.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/

相关文章:

javascript - 菜单切换图标错误

javascript - 有没有更有效的方法来抓取大量 URL(> 30k)?

javascript检查DOM元素是否存在最佳实践

javascript - 在 Django 中使用 Ajax 更新 html 页面上的信息

jquery - 为移动设备调整 reCaptcha 的大小/样式

javascript - ScrollTo 方法在 Edge 中不起作用

javascript - 使用 Javascript 将所有 span-tags 更改为 label-tags?

javascript - 是否可以从数组中获取属性列表并将它们存储在 const 变量中?

javascript - 使用 JQuery 获取部分 className 返回 null

javascript - 在多个页面上使用多个 jQuery 插件?