發布時間:2021-03-24 19:24 作者:獨孤劍 閱讀:1997
$('username').val('admin');直接用$來獲取dom節點的方式也非常便捷方便,那么他是怎么實現的呢?
function Dom(selector) { this.dom = document.querySelector(selector); this.val = function (content) { if (content) { this.dom.value = content } else { return this.dom.value; } } } function $(selector) { return new Dom(selector); } // 調用 $('input').val('value');$()是一個function,這個function會返回一個new Dom的對象,這個new Dom的對象里寫一些方法,就達到jq的這樣效果了。
實際
之后看了jquery源碼的寫法,果然不同凡響……
(function (window, undefined) { jQuery = function (selector, context) { return new jQuery.fn.init(selector, context); } jQuery.fn = jQuery.prototype = { init: function (selector, context) { this.dom = document.querySelector(selector) }, val: function (content) { if (content) { this.dom.value = content } else { return this.dom.value; } } } jQuery.fn.init.prototype = jQuery.fn; window.$ = jQuery; })(window); // 調用 $('input').val('value');首先,將jquery的代碼寫在一個匿名函數里,這樣避免了重復命名對變量的影響,通過window.$ = jQuery;把$掛在window下,實現域外使用$的操作。
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞