當您在輸入中輸入內容時,我希望它始終在末尾添加“ h”(h - 小時)。輸入“21”時,輸入值應為“21 h”。輸入“37”時,輸入值應為“37 h”等。
<input type="text" class="input">
$(".input").on('input', function(){
let input = $(this).val();
$(this).val(input " h");
})
當您輸入“21”時,上面的代碼給出“2 h1 h”。如何在整個值的末尾添加“h”而不是將其添加到每個輸入的字符中?(我不能<p>在輸入后添加標簽)
uj5u.com熱心網友回復:
如果您知道您將只有數字輸入,您可以使用以下內容洗掉所有不是數字的字符。
$(".input").on('input', function(){
let input = $(this).val();
input = input.replace(/[^0-9]/g, '').trim();
$(this).val(input " h");
})
退格事件:
$(".input").on('keyup', function(e) {
if (e.keyCode == 8) {
let input = $(this).val();
input = input.replace(/[^0-9]/g, '').trim();
input = input.substring(0, input.length - 1);
$(this).val(input " h");
}
});
您可以將邏輯提取到一個新函式getInput中,以實作更好的代碼可讀性和管理。
const getInput = (input, del) => {
input = input.replace(/[^0-9]/g, '').trim();
if (del) input = input.substring(0, input.length - 1);
return `${input} h`;
}
$(".input").on('input', () => $(this).val(getInput($(this).val())))
$(".input").on('keyup', () => {
if (e.keyCode === 8) $(this).val(getInput($(this).val(), true));
});
如果您想要 CSS 解決方案,請參考此答案https://stackoverflow.com/a/49797347/6895166
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515201.html
上一篇:大PHP陣列到可讀的json
