我制作了一个带有添加按钮的动态表单,该按钮使用表单的克隆创建一个新的分区,但具有不同的 ID。但是,我还希望每个分区都有一个删除按钮,可以删除它所在的分区,包括按钮本身。
我熟悉 JQuery.remove()
方法,但在选择按钮所在的分区时遇到问题。
<div id="attendees">
<div id="att1" class="attendee">
<form name="droplist" action="html_form_action.asp" method = "get">
<fieldset>
<legend><span class="legend">Filter</span></legend>
<label for="select">Category: </label>
<select id="select" size="1" >
<option value=" " selected="selected"> </option>
<option value="employees">Number of Employees</option>
<option value="hits">Hits on TechCrunch</option>
<option value="time_founded">Time Founded</option>
<option value="total_money">Total Money</option>
</select>
<div id='radioContainer' style="display:block;">
<input type="radio" id="condition" name="button" value="more"/> <label for="condition"> > </label></br>
<input type="radio" id="condition1" name="button" value="less"/> <label for="condition1"> < </label>
</div>
<div id='radioContainerTime' style="display:block;">
<input type="radio" id="condition2" name="button" value="later"/> <label for="condition"> After </label></br>
<input type="radio" id="condition3" name="button" value="earlier"/> <label for="condition1"> Before </label>
</div>
<div id = "text_box" style="display:block;">
<label for="input_value">Amount: </label>
<input type="text" id="box" name="input_value" value="textIn" />
</div>
<button>remove</button>
</fieldset>
</form>
</div>
<a href="#" class="add">Add more</a>
</div>
到目前为止,我的 JavaScript 是这样的:
$(function(){
var template = $('#attendees .attendee:first').clone(),
attendeesCount = 1;
var addAttendee = function(){
attendeesCount++;
var attendee = template.clone().find(':input').each(function(){
var newId = this.id.substring(0, this.id.length-1) + attendeesCount;
$(this).prev().attr('for', newId); // update label for (assume prev sib is label)
this.name = this.id = newId; // update id and name (assume the same)
}).end() // back to .attendee
.attr('id', 'att' + attendeesCount) // update attendee id
.prependTo('#attendees'); // add to container
};
$('.add').click(addAttendee); // attach event
});
$("button").click(function () {
$this.remove();
});