亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Plain Vanilla Javascript 中創建 .hide()

在 Plain Vanilla Javascript 中創建 .hide()

阿波羅的戰車 2023-12-14 16:26:15
完全避免使用 jQuery,我今天開始嘗試讓自己變得像這樣:$('#myDiv').hide();目標是它將適用.style.display = 'none'于#myDiv.因此,我們了解到以下內容是一個與 jQuery 稍微相似的選擇器:var $ = s => document.querySelectorAll.bind(document)(s).length > 1 ?   document.querySelectorAll.bind(document)(s) : document.querySelector.bind(document)(s);使用它時要小心,因為它可以返回多個元素,您可能需要使用其中的.forEach(function(el,i){el.doSomething();});語法。所以,我嘗試創建一個簡單的$(...).hide()函數,如下所示:$.__proto__.hide = function(){this.forEach(function(el,i){el.style.display='none';});};不幸的是,__proto__現在已被棄用,即使您忽略這一點,除非您執行以下操作,否則上述內容也不會起作用:$('#myDIV').__proto__.hide = function(){this.forEach(function(el,i){el.style.display='none';});};使用普通 Javascript 通過函數擴展我的$對象的技術是什么?.hide()
查看完整描述

2 回答

?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

這里的主要問題是您直接返回querySelectororquerySelectorAll結果。您可以將其包裝在您自己的類中,您可以使用方法輕松擴展該類。


class ElementsHelper {

  constructor(elements) {

    this.elements = elements;

  }


  // helper to simplify iterating `this.elements` and returning `this`

  forEach(fn) {

    this.elements.forEach(fn);

    return this;

  }


  hide() {

    return this.forEach(element => element.style.display = "none");

  }


  click(fn) {

    return this.forEach(element => element.addEventListener("click", fn));

  }


}


function $(selector) {

  return new ElementsHelper(document.querySelectorAll(selector));

}

通過上述操作,您現在可以執行以下操作:


$('#myDiv').hide();


查看完整回答
反對 回復 2023-12-14
?
MM們

TA貢獻1886條經驗 獲得超2個贊

你基本上有兩個選擇:

  1. 像 jQuery 一樣使用你自己的對象,或者

  2. 擴展內置原型。

  3. 返回每個單獨的結果對象時對其進行擴展

我可能會使用方法#1,也許是擴展Array(或通過組合使用數組)。

你似乎更喜歡方法#2。通常不建議這樣做,因為一旦開始組合來自多個位置的腳本,就會遇到潛在的沖突。但在應用程序(而不是庫)內,這不一定不合理。

在您的情況下,如果您的$函數返回 的結果querySelectorAll,它將返回 a?NodeList,并且您可以擴展NodeList.prototype。每當擴展原型時,始終使用Object.defineProperty(或類似的)來定義不可枚舉的屬性。例如:

Object.defineProperty(NodeList.prototype, "hide", {

? ? value() {

? ? ? ? this.forEach(/*...*/);

? ? ? ? return this;

? ? },

? ? writable: true,

? ? configurable: true

});

實例:

Object.defineProperty(NodeList.prototype, "hide", {

? ? value() {

? ? ? ? // This isn't a great "hide", it's just for

? ? ? ? // the purposes of showing the plumbing

? ? ? ? this.forEach(el => el.style.display = "none");

? ? ? ? return this;

? ? },

? ? writable: true,

? ? configurable: true

});


const $ = selector => document.querySelectorAll(selector);


setTimeout(() => {

? ? $(".a").hide();

? ? console.log("Hid .a elements");

}, 800);

<div class="a">a</div>

<div class="b">b</div>

<div class="c">c</div>

不幸的是,__proto__現在已被棄用

這是真的,但Object.getPrototypeOf不是,只是__proto__訪問器屬性(它只是為了向后兼容而添加到規范中)。


查看完整回答
反對 回復 2023-12-14
  • 2 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號