我有一些输入文本字段,由用户即时生成(通过javascript)。我希望这些字段只接受整数,所以我使用的是字母数字插件。该插件在页面加载时已经存在的元素上按预期工作,但它不适用于新的动态元素。我怎样才能将新元素绑定到这个插件?谢谢!
以下是一些示例代码。
答案 0 :(得分:3)
简单快速修复 - 更改:
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
到
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').numeric().appendTo(scntDiv);
请注意,动态插入的字段都具有相同的ID。这不好,你应该为每个输入使用唯一的id,或者根本不使用id。
答案 1 :(得分:2)
你去吧
http://jsfiddle.net/tZPg4/781/
你只需要这个
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv).find("input").numeric();
问题不在于您使用live
,因为您没有在新创建的输入框上运行numberic
插件。
答案 2 :(得分:1)
live
在这里不会帮到你。每当您添加新输入时,您都必须重新启动插件:
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>')
.appendTo(scntDiv)
.find('input').numeric();
答案 3 :(得分:0)
一种方法是为动态输入调用字母数字插件:
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
$('#p_scents p:last input').numeric(); // Added this line...
return false;
});
答案 4 :(得分:0)
只需在新添加的输入字段上调用.numeric()方法即可。在执行.appendTo(scntDiv)之后,您调用:
scntDiv.children('p:last .intonly').numeric();
完整代码: