我想為自己制作一個速記庫,例如:縮短querySelector為get.
有沒有辦法只回傳沒有的方法document?
例子:
function get(selector) {
return .querySelector(selector)
}
謝謝。
uj5u.com熱心網友回復:
您必須呼叫.querySelector檔案或元素。它不能被忽略。雖然你可以將它傳遞給函式......
const get = (context, selector) => context.querySelector(selector);
get(document, '.foo');
document每次呼叫時都必須撰寫它會非常重復。把它放在函式里面就行了,沒有錯。
const get = (selector) => document.querySelector(selector);
另一種選擇(我不推薦,因為它會改變內置物件)是將您的方法添加到document.
document.get = function(selector){
return this.querySelector(selector);
};
要么
document.get = (selector) => document.querySelector(selector);
uj5u.com熱心網友回復:
const get = document.querySelector.bind(document);
這將起作用,因為它將檔案的背景關系保留到 querySelector 的 this
get('*') // will work while defining it as const get = document.querySelector wouldnt
編輯:為什么不贊成這是真的
uj5u.com熱心網友回復:
我建議使用 Jquery。它在前端行業被廣泛接受,可以滿足您的要求,并且可以將其用于其他組織級別的專案,而不僅僅是個人專案。
只需在您的 html 標頭中包含這行代碼:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454833.html
標籤:javascript 功能
