[英]Removing a newly created element in JavaScript with creating a button
我通过此代码在<div>
添加了<p>
并创建了一个按钮。
var selectedId = this.value;
var divElem = $("#selectedItem");
var bElem = document.createElement("Button");
var bElemInnerHTML = document.createTextNode("Erase");
bElem.addEventListener('click', function () {
remove(this.value);
}, true);
bElem.appendChild(bElemInnerHTML);
var pElem = document.createElement("p");
var pElemInnerHTML = document.createTextNode(this.value);
pElem.setAttribute('id', selectedId);
alert(pElem.getAttribute('id'));
pElem.style.fontSize = '25px';
pElem.style.textAlign = 'center';
pElem.style.margin = '5px';
pElem.appendChild(pElemInnerHTML);
pElem.appendChild(bElem);
divElem.append(pElem);
我添加到按钮上,以在单击时运行remove
功能
function remove(id){
var emad = document.getElementById(id);
emad.parentNode.removeChild(emad);}'
但这不起作用。
bElem.addEventListener('click', function () {
remove(this.value);
}, true);
上述上下文中的this.value引用Button
元素的value属性(它是一个字符串),而不是Button的ID。 另外,您还没有定义ID,因此this.id
将返回""
(空字符串)
bElem.addEventListener('click', function () {
remove(this.id);
}, true);
您可以修改remove()
来接受对象:
function remove(btn){
emad.parentNode.removeChild(btn);
}
bElem.addEventListener('click', function () {
remove(this);
}, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.