gpt4 book ai didi

javascript - 更改 keyup 上的输入字段以匹配 MAC 地址格式

转载 作者:行者123 更新时间:2023-11-30 08:24:08 25 4
gpt4 key购买 nike

我没有太多使用 JavaScript 或 jQuery 的经验。

我尝试使用 Tampermonkey 自动更正 MAC 地址的输入字段。

站点需要格式为 00:00:00:00:00:00 的 MAC 地址。

所以我为 Tampermonkey 编写了这个脚本,所以它会在我输入时自动添加冒号:

// ==UserScript==
// @name Name
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Adds colons to the mac adress of the Mac Field
// @author You
// @match Somesite
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
document.getElementById("MAC").addEventListener('keyup', function() {
var mac = document.getElementById('MAC').value;
var macs = mac.split('');
var colons = ["2", "5", "8", "11", "14"];
for (var col in colons) {
if (macs[col] == "-") {
macs[col] = ":";
} else if (macs[col] != "") {

} else if (macs[col] != ":") {
var colo = col + 1;
macs[colo] = macs[col];
macs[col] = ":";
}
}
mac = macs.toString();
});
<input id=MAC />

但它不起作用。输入字段的 ID 是 MAC

我哪里做错了,错了多少?

解决方案

感谢@i-wreSTLed-a-bear-once 和@freginold 提供我的最佳解决方案

我现在使用的是来自@freginold 的略微改动的版本

var back = true;
function isHex(char) {
// check if char is a hex char
if (!isNaN(parseInt(char))) {
return true;
} else {
switch (char.toLowerCase()) {
case "a":
case "b":
case "c":
case "d":
case "e":
case "f":
return true;
}
return false;
}
}
document.getElementById("MAC").addEventListener('keydown', function() {
var key = event.keyCode || event.charCode;

if( key == 8 || key == 46 ) {
back = false;
}
});

document.getElementById("MAC").addEventListener('keyup', function() {
var key = event.keyCode || event.charCode;


var mac = document.getElementById('MAC').value;
var newMac = mac.replace("-", ""); // remove any dashes
if ((isHex(mac[mac.length - 1]) && (isHex(mac[mac.length - 2])) && (mac.length <= 16) && (back))) {
// if last two chars are numbers, insert a colon
newMac = newMac + ":";

}
back = true;
document.getElementById('MAC').value = newMac; // put new value into input field

});

最佳答案

  • replace(/[^\d|A-Z]/g, '') 删除任何非字母数字字符
  • match(/.{1,2}/g) 将字符串分成 2 个 block
  • join(":") 加入 block 并在它们之间放置一个冒号

// ==UserScript==
// @name Name
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Adds colons to the mac adress of the Mac Field
// @author You
// @match Somesite
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
document.getElementById("MAC").addEventListener('keyup', function() {
// remove non digits, break it into chunks of 2 and join with a colon
this.value =
(this.value.toUpperCase()
.replace(/[^\d|A-Z]/g, '')
.match(/.{1,2}/g) || [])
.join(":")
});
<input id=MAC />

关于javascript - 更改 keyup 上的输入字段以匹配 MAC 地址格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com