[英]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.