使用javascript添加和删除(特定)表单元素

时间:2011-06-20 00:21:28

标签: javascript html forms dynamic-forms

我有一个textarea,旁边是两个按钮:“添加另一个textarea”和“删除此textarea”

这是我的HTML代码:

<div id="summaryIn">
                            <label for="">Summary of Experience:</label> 
                            <textarea class="TA1" name="mySummary[]" value=""></textarea>
                            <button class="adddel" name="cmdDelSummary[]" id="cmdDelSummary" title="Delete this Summary" onClick="DelSummary('summaryIn');">-</button> 
                            <button class="adddel" id="cmdAddSummary" title="Add Another Summary" onClick="AddSummary('summaryIn');">+</button>
                        </div>

我添加textarea的javascript函数工作正常,但删除按钮不能正常工作,这里是javascript代码:

function DelSummary(divName){
alert(summary_counter);
if (summary_counter == 1)
{
    document.getElementById('cmdDelSummary').disabled=true;
}
else
{
    summaryIn.removeChild(summaryIn.lastChild);
    summary_counter--;
    //alert(summary_counter);
}

}

我一直试图解决这个问题很长一段时间,但直到现在我还没有找到任何解决方案。 。 .i不知道如何索引/引用其他删除按钮,以便removeChild只删除那个特定的textarea,而不是总是提前lastChild..thanks提前:)

2 个答案:

答案 0 :(得分:1)

我认为你必须添加

summaryIn = document.getElementById(divName);

summaryIn.removeChild(summaryIn.lastChild);

答案 1 :(得分:0)

这一行:

summaryIn.removeChild(summaryIn.lastChild);

似乎依赖于将元素名称和id引入引用该元素的全局变量的做法。这是一种尚未被所有浏览器实现的非标准做法。

而是使用符合标准的:

var  summaryIn = document.getElementById('summaryIn');

现在您可以调用其 removeChild 方法。你应该检查你要删除的内容,因为最初“添加另一个摘要”按钮是最后一个元素子项。

修改

按照惯例,以大写字母开头的函数名称是为cosntructors保留的,所以我使用了小写。

从文档中删除div及其内容:

// Go up DOM until reach parent element with tagName
// If no such node found, return undefined.
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el.parentNode) {
    el = el.parentNode;

    if (el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }
}

function delSummary(el){
  var div = upTo(el, 'div');
  div.parentNode.removeChild(div);
}

并称之为:

  <button ... onclick="delSummary(this);" ...>-</button> 

虽然HTML属性名称不区分大小写,但我发现使用驼峰的情况会使它们难以阅读,因此使用小写。

相关问题