您的代码中有几个错误:
$counter = 0;
$("#add").click(function() {
$counter++;
//I removed the `<br />` tag and added a bit of CSS because if you remove the <input /> tags the <br /> tags added with them remain
$("#ipblock").append('<input type="text" name="inputip" id="inputip'+$counter+'" size="22" />');
});
$("#del").click(function() {
//this just makes sure there is actually an element to select before trying to select it
if ($counter) {
//use double quotes to start and stop the string here
$("#inputip"+$counter).remove();
//make sure to refer to `$counter` and not `counter`
$counter = $counter - 1;
}
});
这是一个演示:http: //jsfiddle.net/fQBNE/29/
我添加了这个 CSS,以便在您的调用<br />
中不需要该标签:.append()
/*This will put each input on its own line*/
#ipblock > input {
display:block;
}
更新
在没有变量的情况下完成此操作的另一种方法$counter
是选择click 事件处理程序input
中的最后一个元素:#del
$("#add").click(function() {
//notice no ID is needed
$("#ipblock").append('<input type="text" name="inputip" size="22" />');
});
$("#del").click(function() {
//first try to select the last inputip element
var $ele = $('#ipblock').children('input[name="inputip"]').last();
//only proceed if an element has been selected
if ($ele.length) {
//and now remove the element
$ele.remove();
}
});
这是一个演示:http: //jsfiddle.net/fQBNE/31/