I'm new to Javascript, and trying to design a form with elements that are created and deleted by clicks on links without submitting a form.
The script depends on getting the unique id of a clicked button (css and <a>
link), and calculating the id of the row containing the link, and then deleting the entire <tr>
element.
For this, I'm trying to get the id of a clicked link. The link and the elements it is embedded in, is itself generated by javascript on clicking another button.
I tried the following:
var btnDel=document.createElement("a");
btnDel.id="NS_D"+count;
btnDel.className="btn btn-danger";
btnDel.addEventListener('click', function()
{
alert(e.id);
}, false);
var btnText=document.createElement("span");
btnText.className="btn-label";
btnText.innerHTML="Delete";
btnDel.appendChild(btnText);
td.appendChild(btnDel);
Though the button is generated, I'm not getting an alert as expected. Where can I have gone wrong?
In the event handler, this
refers to the element, so you can do:
alert(this.id);
To get to the <tr>
you can go up the tree using parentNode
:
console.log(this.parentNode.parentNode);
You need use this
rather than e
:
alert(this.id);
in your event handler.
(You also need to get used to running your code with the Console visible - that would have told you that the reason you weren't seeing your alert
is that e
doesn't exist.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.