简体   繁体   English

试图用Javascript删除元素

[英]Trying to delete element with Javascript

When a client clicks the "buy" button, I create a popup on screen which allows them to fill in a purchase form. 当客户点击“购买”按钮时,我会在屏幕上创建一个弹出窗口,允许他们填写购买表单。 On the poput I want to have a "x" button so they can close it and return to the main website. 在poput我想要一个“x”按钮,以便他们可以关闭它并返回主网站。

The code I run to generate the popup is: 我运行以生成弹出窗口的代码是:

var o = document.createElement('div');
o.className = 'overlay';

var p = document.createElement('div');
p.className = 'buyticketid';
p.setAttribute('id','buy-ticket');

var cb = document.createElement('p');
cb.className = 'closeButton';
cb.setAttribute('onclick','close()');
cb.setAttribute('title','Close');
cb.setAttribute('id','close-btn');
var x = document.createTextNode('x');
cb.appendChild(x);

p.appendChild(cb);

document.getElementsByTagName('body')[0].appendChild(o);
document.getElementsByTagName('body')[0].appendChild(p);

The code I use to try and delete the popup (ID = 'buy-ticket') is: 我用来尝试删除弹出窗口的代码(ID ='buy-ticket')是:

function close(){

var element = document.getElementById("buy-ticket");
element.parentNode.removeChild(element);

}

For some reason when I click the close button nothing happens. 出于某种原因,当我点击关闭按钮时没有任何反应。 If anyone could point me in the right direction that would be awesome. 如果有人能指出我正确的方向,那将是非常棒的。

you can assign a click handler to a dom element like this: element.onclick = callback; 您可以将点击处理程序分配给dom元素,如下所示: element.onclick = callback; where callback is your callback function. 回调是你的回调函数。

This works as expected: 这按预期工作:

function close(){
    var element = document.getElementById("buy-ticket");
    element.parentNode.removeChild(element);
}  

var o = document.createElement('div');
o.className = 'overlay';

var p = document.createElement('div');
p.className = 'buyticketid';
p.setAttribute('id','buy-ticket');

var cb = document.createElement('p');
cb.className = 'closeButton';
cb.onclick = close;
cb.setAttribute('title','Close');
cb.setAttribute('id','close-btn');
var x = document.createTextNode('x');
cb.appendChild(x);

p.appendChild(cb);

document.getElementsByTagName('body')[0].appendChild(o);
document.getElementsByTagName('body')[0].appendChild(p);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM