这段代码有什么问题?只有首先添加和删除链接才有效...
<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>
当您绑定click()处理程序,只有一个Add
要绑定到的页面上的链接。使用live() http://api.jquery.com/live/捕获页面上尚未出现的元素的点击事件:
$(".addButton").live("click", function () {
工作演示:http://jsfiddle.net/u9hvp/ http://jsfiddle.net/u9hvp/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)