jq 风格 - 动态 dom 小框架

本贴最后更新于 309 天前,其中的信息可能已经东海扬尘

什么?有 jq 为啥还要自己写框架?因为它很多不需要的功能,白白浪费加载时间,不想再等啦!

史山代码养成记之——链式 dom 一行生命周期就结束。

示例

$.c("div").t("你是一个一个一个啊").a(document.body).o("click", (e)=> {
  $.c("span").t("啊啊").a(e.target);
});

效果:屏幕动态渲染一句话,每次点击会在后面追加 啊啊 两个字。

源码

// 基于可链式调用的类进行动态dom操作
(()=> {

  function S(e) {

    if(!(e instanceof HTMLElement)) throw new TypeError("Element only");
    if(!(this instanceof S)) return new S(e);

    this.e = e;

  }

  S.prototype = {
    html(t) {this.e.innerHTML = t;return this;},
    text(t) {this.e.textContent = t;return this;},
    src(t) {this.e.src = t;return this;},
    at(e) {e.append(this.e);return this;},
    on(s,f) {this.e.addEventListener(s,f);return this;},
    class(s) {this.e.className = s; return this;},
    id(s) {this.e.id = s;return this;}
  };
  for(const n of Object.keys(S.prototype))
   Object.defineProperty(S.prototype, n[0], {value:S.prototype[n]});


  S.c = S.create = (t)=> new S(document.createElement(t));
  S.i = S.getId = (t)=> new S(document.getElementById(t));
  S.q = S.getQuery = (t)=> new S(document.querySelector(t));

  window.$ = S;

})();

Feat.

  • 可缩写可全称
  • 功能随便添加,链式调用首字母缩写屡试不爽
  • 缩短手写代码量

结语

以前不太喜欢面向对象,直接用 $.c("div", "233", document.body); 这样的用参数位置判断功能的写法,但扩展性和可读性都差些。链式调用还是很强的 👍

  • jQuery

    jQuery 是一套跨浏览器的 JavaScript 库,强化 HTML 与 JavaScript 之间的操作。由 John Resig 在 2006 年 1 月的 BarCamp NYC 上释出第一个版本。全球约有 28% 的网站使用 jQuery,是非常受欢迎的 JavaScript 库。

    63 引用 • 134 回帖 • 741 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...