我有一个表单,允许用户单击“添加”按钮以显示更多表单字段。然后,id
发生更改,以便当用户再次单击时,会出现一组不同的表单字段。第一个实例按预期工作,但是,我无法显示第二组字段。我是 JS 新手,所以我不太确定我在这里缺少什么。谢谢!
HTML:
<p>
<table>
<tr>
<td width="250px">
Shipping Method
</td>
<td>
<select name="shipmeth_id">
<option value="1">UPS</option>
<option value="2">FedEx</option>
</select>
</td>
</tr>
<tr>
<td>
Account Number
</td>
<td>
<input id="ship_num" name="ship_num" type="text" />
</td>
</tr>
<tr>
<td>
Zip Code
</td>
<td>
<input id="ship_zip" name="ship_zip" type="text" />
</td>
</tr>
</table>
</p>
<p class="extra_ship" style="display:none;">
<table>
<tr>
<td width="250px">
Shipping Method
</td>
<td>
<select name="shipmeth_id2">
<option value="1">UPS</option>
<option value="2">FedEx</option>
</select>
</td>
</tr>
<tr>
<td>
Account Number
</td>
<td>
<input id="ship_num" name="ship_num" type="text" />
</td>
</tr>
<tr>
<td>
Zip Code
</td>
<td>
<input id="ship_zip" name="ship_zip" type="text" />
</td>
</tr>
</table>
</p>
<p class="extra_ship2" style="display:none;">
<table>
<tr>
<td width="250px">
Shipping Method
</td>
<td>
<select name="shipmeth_id3">
<option value="1">UPS</option>
<option value="2">FedEx</option>
</select>
</td>
</tr>
<tr>
<td>
Account Number
</td>
<td>
<input id="ship_num" name="ship_num" type="text" />
</td>
</tr>
<tr>
<td>
Zip Code
</td>
<td>
<input id="ship_zip" name="ship_zip" type="text" />
</td>
</tr>
</table>
</p>
<p>
<table>
<tr>
<td width="250px" style="text-align:right;">
Add Another Account
</td>
<td width="50px">
</td>
<td>
<button name="add_ship" value="add" type="button" id="add_1" class="add_button" >
<img src="img/plus_button.png">
</button>
</td>
</tr>
</table>
</p>
还有 JS:
<script type="text/javascript">
$('#add_1').click(function() {
$('.extra_ship').show();
document.getElementById('add_1').id = 'add_2';
});
$('#add_2').click(function() {
$('.extra_ship2').show();
});
</script>
最佳答案
虽然您可以使用该设置,但不要更改id
。尝试使用这个:
<button name="add_ship" value="add" type="button" id="add_1" class="add_button" data-state="first_step">
请注意标记末尾的 data-state="first_step"
属性。
还有:
$('#add_1').click(function() {
var $this = $(this),
state = $this.attr("data-state");
if (state === "first_step") {
$('.extra_ship').show();
$this.attr("data-state", "second_step");
} else if (state === "second_step") {
$('.extra_ship2').show();
}
});
关于javascript - 更改 id 后元素不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16615676/