我有一些输入文本字段正在生成的飞行(通过JavaScript)由用户。我希望这些字段只接受整数,所以我使用字母数字插件。该插件按预期在页面加载时已存在的元素上工作,但不适用于新的即时元素。我怎样才能将新元素绑定到这个插件?谢谢!jquery绑定插件生活元素
这是一些示例代码。
http://jsfiddle.net/ctown4life/tZPg4/780/
我有一些输入文本字段正在生成的飞行(通过JavaScript)由用户。我希望这些字段只接受整数,所以我使用字母数字插件。该插件按预期在页面加载时已存在的元素上工作,但不适用于新的即时元素。我怎样才能将新元素绑定到这个插件?谢谢!jquery绑定插件生活元素
这是一些示例代码。
http://jsfiddle.net/ctown4life/tZPg4/780/
简单速战速决 - 变化:
$('<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。
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();
在这里你去
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
插件。
的一个方法是调用字母数字插件为您的动态投入:
$('#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;
});
就叫上新追加的输入字段的.numeric()方法。做.appendTo(scntDiv)后,您拨打:
scntDiv.children('p:last .intonly').numeric();
全码:
+1实现呼叫到'数字()'可以在调用之前插入'appendTo(scntDiv)'。 – Gus
当然!这很棒,谢谢你的帮助。 – ctown4life