![](/img/trans.png)
[英]How to find which node was clicked and remove its parent using jquery
[英]How to find parent node and remove child
我对JavaScript缺乏经验,并且在进行了大量的搜索和审阅其他线程之后,我很难理解如何以与我的用例类似的方式从Web表单中动态删除字段。 (或更可能,我就是不明白!)。
我的理解是,没有引用父节点就无法从DOM中删除元素。 但是,我不完全确定使用removeChild()时应在代码中引用的父节点是什么。 我怀疑这是我的HTML中的内容; 如果有人能指出我正确的方向,那就太好了。
HTML <body>
<div>
<body>
<div class="wrapper">
<div class="sidebar" text-align="center">
myFormFieldLabel <button onclick="myFunction()">add</button></p>
</div>
<div class="main" text-align="center">
<form name="myForm" action="/" method="POST">
some text goes here.
</br>
<hr>
</br>
<div class="fields" id="rf1">
<!--added form fields will appear here-->
</div></p>
</div>
<div class="submit">
<input type="submit" value="Submit" />
</form>
</div>
</div>
动态创建字段的JavaScript:
function myFunction(){
var r = document.createElement('span');
var y = document.createElement("INPUT")
var p = document.createElement('p');
var g = document.createElement("IMG");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "myFormField");
g.setAttribute("src", "delete.png");
g.setAttribute("onclick", //should remove entire form input field(span)//);
increment();
y.setAttribute("Name", "myField" + "~input_" + i);
r.appendChild(y);
r.appendChild(g);
r.appendChild(p);
document.getElementById("rf1").appendChild(r);
}
通常,我在此处调整代码时遇到的错误是存在Uncaught TypeError: Cannot read property 'removeChild' of null
要从文档中删除节点,首先应从JavaScript代码中为其指定ID。 这将使以后以编程方式删除它变得容易得多。
例如:
var r = document.createElement("span");
r.id = "myID";
var y = document.createElement("INPUT")
var p = document.createElement('p');
var g = document.createElement("IMG");
...
// Later
var p = document.getElementById("myID");
p.parentNode.removeChild(p);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.