我对 JavaScript 的经验不是很丰富,但这段代码与我正在寻找的代码类似,特别是其中包含“删除字段”链接的地方。这是 JavaScript 函数:
//Add more fields dynamically.
function addField(field,area,limit) {
if(!document.getElementById) return; //Prevent older browsers from getting any further.
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.
//Find the count of the last element of the list. It will be in the format '<field><number>'. If the
// field given in the argument is 'friend_' the last id will be 'friend_4'.
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
var count = Number(last.split("_")[1]) + 1;
//If the maximum number of elements have been reached, exit the function.
// If the given limit is lower than 0, infinite number of fields can be created.
if(count > limit && limit > 0) return;
if(document.createElement) { //W3C Dom method.
var li = document.createElement("li");
var input = document.createElement("input");
input.id = field+count;
input.name = field+count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
} else { //Older Method
field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' /></li>";
}
}
以下是该表单的 HTML:
<form name="frm" method="POST">
<strong>Neutral List</strong><br />
<ol id="neutrals_area">
<li><input type="text" name="neutral_1" id="neutral_1" /> <a style="cursor:pointer;color:blue;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove Field</a></li>
<li><input type="text" name="neutral_2" id="neutral_2" /> <a style="cursor:pointer;color:blue;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove Field</a></li>
<li><input type="text" name="neutral_3" id="neutral_3" /> <a style="cursor:pointer;color:blue;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove Field</a></li>
<li><input type="text" name="neutral_4" id="neutral_4" /> <a style="cursor:pointer;color:blue;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove Field</a></li>
<li><input type="text" name="neutral_5" id="neutral_5" /> <a style="cursor:pointer;color:blue;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove Field</a></li>
</ol>
<input type="button" value="Add Neutral Field" onclick="addField('neutrals_area','neutral_',0);" />
</form>
但是,我希望使用“删除链接”代码生成其他字段,而不仅仅是脚本中包含代码的字段。我知道必须调整自定义函数以包含该行为,但在尝试使该函数正常工作时遇到了各种麻烦。在旧方法中,在 addField 函数底部的“} else {”之后,通过编辑代码来执行此操作似乎很简单:
} else { //Older Method
field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' /><a style="cursor:pointer;color:blue;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove Field</a></li>";
}
但是,我很困惑如何将它包含在 W3C DOM 方法中?