進階的 Javascript 分享

分享常見的 Javascript 副程式,索引:


個案1:檢查輸入內容是否為數字

輸入框要求使用者輸入 5位的數字,就是5個整數,部份的數字會誤判為英文,例如:數字 9 判斷為英文 g, 數字 0 判斷為英文 o,解法是先判斷驗證碼是否為正整數:

function isInteger(value) {
    return /^-?\d+$/.test(value);
}

更多進階數字判斷:
https://stackoverflow.max-everyday.com/2024/03/javascript-isnumeric/


個案2:自動登入帳密,並延遲按下送出按鈕

let user_id = "your-account";
let user_password = "your-password";
let login_delay_interval = 3000;
$("#account_selector").val(user_id);
$("#password_selector").val(user_password);
setTimeout(() => {
    $("#submit_selecotor").click();
}, login_delay_interval);

附註:增加了 setTimeout 進行延遲,如果不需延遲可以拿掉 setTimeout()。


個案3:關鍵字比對需「全部符合」

當輸入的關鍵字使用了空格” “, 例如:”12/01 16:45″, 代表應該要同時符合”12/01” 而且也要出現 “16:45”

// AND logic
if (area_keyword.indexOf(" ") > 0) {
    keyword_control_symbol = true;
    const keyword_array = area_keyword.split(" ");
    let contain = true;
    for (var j = 0; j < keyword_array.length; j++) {
        if (keyword_array[j] == "") continue;
        if (html_text.indexOf(keyword_array[j]) == -1) {
            contain = false;
            break;
        }
    }
    if (contain) {
        // 全部都符合
    }
}

個案4:用關鍵字移除不要的區塊內容

下面這幾行就可以把所有 div.ticket-unit 中不要的關鍵字的區塊,使用 .remove() 進行移除,當然也可以用 .hide() 藏起來就好了。

var exclude_keyword_array = ["輪椅", "身障", "身心障礙", "Restricted View", "Wheelchair", "燈柱遮蔽", "視線不完整"];
for (let i = 0; i < exclude_keyword_array.length; i++) {
    $("#target_selector").each(function() {
        let html_text = $(this).text();
        if (html_text.indexOf(exclude_keyword_array[i]) > -1) {
            $(this).remove();
        }
    });
}