jQuery 使用jquery动态添加文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4204122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically add textbox using jquery
提问by Hector Barbossa
What's wrong with this code ? Only first add and remove link is working...
这段代码有什么问题?只有首先添加和删除链接才有效...
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$(".addButton").click(function () {
if(counter>5){
alert("Only 5 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<TABLE><TR><TD>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ></TD><TD><input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ></TD> <TD><a href="#" value="addButton" class="addButton">Add</a> <a href="#" value="removeButton" class="removeButton">Remove</a></TD></TR></TABLE>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$(".removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<TR><TD><input type='textbox' id='textbox1' ></TD> <TD><input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ></TD> <TD><a href="#" value="addButton" class="addButton">Add</a> <a href="#" value="removeButton" class="removeButton">Remove</a></TD></TR>
</div>
</div>
</body>
</html>
回答by Andy E
When you bind the click()handler, there's only one Add
link on the page to bind to. Use live()to capture click events for elements that aren't on the page yet:
当您绑定click()处理程序时,Add
页面上只有一个链接要绑定到。使用live()捕获尚未出现在页面上的元素的点击事件:
$(".addButton").live("click", function () {
Working demo: http://jsfiddle.net/u9hvp/
工作演示:http: //jsfiddle.net/u9hvp/
回答by jlunavtgrad
Use of live() has been depreciated, and removed since Andy E's post. The same functionality is now supported using the following syntax:
自 Andy E 的帖子以来,live() 的使用已被贬值,并被删除。现在使用以下语法支持相同的功能:
$(document).on("click", ".removeButton", function () {
$(document).on("click", ".removeButton", function () {
回答by Selvakumar Kaliyappan
you just add this file in your folder its works fine...!
您只需将此文件添加到您的文件夹中即可正常工作......!
jquery-1.3.2.min.js
jquery-1.3.2.min.js