我正在使用一个表单,其中包含添加更多城市的选项,可以输入多个城市名称。还有一个按钮t0也删除了字段。 它工作正常,但问题是在下面的代码我得到第一个城市的删除按钮也不正确。
那么如何从第一组输入框中删除“删除”按钮。对于所有新生成的字段,应继续删除按钮。
我从此网站http://www.quirksmode.org/dom/domform.html
获取此代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Extending forms</title>
<script type="text/javascript" src="./Javascript - Extending forms_files/quirksmode.js"></script>
<script type="text/javascript">
<!--
var counter = 0;
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
// -->
</script>
</head>
<body>
<!--This prat will be dynamically generated on clicking the add more button (and this is the default one to be shown in the page)-->
<div id="readroot" style="display: none">
<input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">
<label for="city">City:</label> <input type="text" class="pssng1" name="city" value="" />
<label for="days">Days:</label> <input type="text" class="pssng1" name="days" value="" />
</div>
<!--This prat will be dynamically generated on clicking the add more button-->
<form method="post" >
<div id="" style="display: block; "></div>
<span id="writeroot"></span>
<input type="button" id="moreFields" value="Add more!">
</form>
</body>
</html>
答案 0 :(得分:1)
修改您的JavaScript;
<script type="text/javascript">
<!--
var counter = 0;
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=1;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
// -->
</script>