gpt4 book ai didi

javascript - 将 jQuery inputmask 附加到 DOM 元素

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

我正在使用 RobinHerbot 的输入掩码,但似乎无法弄清楚如何将其附加到 DOM 元素。我遇到过几个“解决方案”,但没有一个能按照我创建新字段的方式工作。我尝试创建一个函数以将其附加到新添加的字段,因为我知道代码无法在文档就绪函数中的 DOM 上运行,但事实证明这也没有帮助。

这是一个 jsfiddle 示例:jsfiddle

JS

var count_2 = 5;

$(document).ready(function () {

$('#btnAdd').click(function () {
count_2 = count_2 + 2;
$('#Table tr:last').after('<tr><td>' +
'<p class=\"null_temp\">' +
'<input type=\"text\" name=\"temp' + count_2 + '\" id=\"temp' + count_2 + '\" placeholder=\"Time\" size=\"10\" maxlength=\"8\" value=\"\" class=\"total_time_regex\" />' +
'</td></tr>');
});

$('.total_time_regex').inputmask('Regex', {
regex: "^([0-9]{1,4}:[0-5][0-9])$"
});
});

$(function() {
$('.total_time_regex').inputmask('Regex', {
regex: "^([-][0-9]{1,4}:[0-5][0-9])|([0-9]{1,4}:[0-5][0-9])$"
});
});

HTML

<table style="width: 70%" id="Table" name="Table">
<tr>
<th>Time</th>
</tr>
<tr>
<td>
<p class="null_temp">
<input type="text" name="temp1" id="temp1" placeholder="Time" size="10" maxlength="8" value="" class="total_time_regex" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />

CSS

#Table {
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse:collapse;
}
#Table td, #Table th {
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#Table th {
font-size:1.4em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#fff;
}
#Table tr.alt td {
color:#000;
background-color:#EAF2D3;
}

非常感谢您的帮助,因为我仍在学习如何处理 DOM 元素。提前致谢!

最佳答案

您只在文档准备好时调用一次输入屏蔽函数,这会导致只有最初创建的时间框应用了屏蔽。您还需要将它添加到页面加载后添加的每个输入。您可以使用相同的 jQuery 调用,它只需要从点击处理程序以及页面加载时调用。我建议将掩码初始化放在函数中,如下所示:

var count_2 = 5;

$(document).ready(function () {

$('#btnAdd').click(function () {
count_2 = count_2 + 2;
$('#Table tr:last').after('<tr><td>' +
'<p class=\"null_temp\">' +
'<input type=\"text\" name=\"temp' + count_2 + '\" id=\"temp' + count_2 + '\" placeholder=\"Time\" size=\"10\" maxlength=\"8\" value=\"\" class=\"total_time_regex\" />' +
'</td></tr>');
addMask();
});

function addMask() {
$('.total_time_regex').inputmask('Regex', {
regex: "^([0-9]{1,4}:[0-5][0-9])$"
});
}
addMask();
});

工作演示链接:https://jsfiddle.net/70kat20w/ .

关于javascript - 将 jQuery inputmask 附加到 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878867/

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