JavaScript 或 jQuery 中各種常用的代碼總結;
移除 class,移除屬性:
// 移除class,移除屬性
$("input").removeClass("hidden").removeAttr("disabled");
「- -」「- -」「- -」「- -」
jQuery 操作 Select:
// https://www.cnblogs.com/shanyou/archive/2011/07/11/2103422.html
// 可直接使用val()方法賦值
$('select').val(2);
「- -」「- -」「- -」「- -」
關於正則分組命名及回調替換:
function fnReplace(html, post_id) {
const fnRegxCB = function () {
// console.log(arguments); // 輸出全部參數,這個對象並不是數組
// 轉換成數組
const arrArgs = Array.prototype.slice.call(arguments);
// 命名分組被放在最後一項中,pop()方法會從原數組中刪除最後一項並返回
const data = arrArgs.pop();
// 調試輸出
console.log(arrArgs, data);
// 字符轉數字
post_id = parseInt(post_id);
data.app_id = parseInt(data.app_id);
// 取餘+3,3<=hash<=9
const hash = ((post_id + data.app_id) % 7) + 3;
console.log(hash, post_id + data.app_id);
return `<a href="${data.url}#${hash}-${post_id}" ${data.attrs}>${data.url}#${hash}-${post_id}</a>`;
};
return html.replace(
/<a href="[^"]+" (?<attrs>[^>]+)>(?<url>https:\/\/app.zblogcn.com\/\?id=(?<app_id>\d+))[^<]*<\/a>/,
fnRegxCB
);
// 不需要回調處理的話是這樣↓
// return html.replace(
// /<a href="[^"]+" (?<attrs>[^>]+)>(?<url>https:\/\/app.zblogcn.com\/\?id=(?<id>\d+))[^<]*<\/a>/,
// `<a href="$<url>#${post_id}" $<attrs>>$<url>#${post_id}</a>`
// );
}
「- -」「- -」「- -」「- -」
obj 轉網址參數:
// obj轉網址參數
const queryString = Object.keys(data)
.map((key) => key + "=" + data[key])
.join("&");
「- -」「- -」「- -」「- -」
obj 鍵值遍歷:
// obj鍵值遍歷
Object.keys(req.headers).forEach(function (key) {
console.log(key, req.headers[key]);
});
「- -」「- -」「- -」「- -」
解除圖片防盜鏈:
// 解除圖片防盜鏈
(() => {
function $na(e) {
return document.querySelectorAll(e);
}
$na("a img").forEach((el) => {
el.setAttribute("referrerPolicy", "no-referrer");
console.log(el.getAttribute("src"));
});
})();
「- -」「- -」「- -」「- -」
並不常用,只是備忘:
(()=>{
for (let index = 0; index <= 13; index++) {
console.log(index,index % 7,Math.abs(index % 7 - 3));
}
})();