【发布时间】:2015-11-23 19:19:00
【问题描述】:
我正在使用 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 元素。提前谢谢!
【问题讨论】:
-
由于输入是动态创建的,所以需要使用event delegation
-
尝试将
inputmask代码放入您的点击事件中。
标签: javascript jquery html css dom