click event not firing on anchor tag

时间:2016-10-20 13:01:00

标签: javascript html

My click event is not firing.

My HTML:

<tr>
    <td>121345</td>
    <!-- Other td-elements -->
    <td><a href = "#" class = "remove-item">Remove</a></td>
</tr>

My Javascript:

window.document.load = function()
{
    document.getElementsByClassName('remove-item').onClick(function(element)
    {
        console.log("element");
        var productId = element.parentElement.parentElement.childElements[0].value;
        console.log(productId);
    });
};

I don't want to use jQuery for this.

2 个答案:

答案 0 :(得分:2)

The problem is that getElementsByClassName returns a collection elements - not a single one because classes can be applied to multiple elements. From the documentation:

Returns an array-like object of all child elements which have all of the given class names.

Just use [0] to access the first element in the return array-like object (the first element with that class).

Also onClick is not the correct way to add an event handler. You may use addEventListener which takes in an event and a handler:

window.document.load = function() {
    document.getElementsByClassName('remove-item')[0].addEventListener("click", function(element) { //add click handler to first element with remove-item class
        console.log("element");
        var productId = element.parentElement.parentElement.childElements[0].value;
        console.log(productId);
    });
}

If your intention is to apply a click handler to each of the elements with the event, you may use Array.prototype.forEach:

var elements = document.getElementsByClassName('remove-item');

Array.prototype.forEach.call(elements, function(currentElement) {
    console.log("element");
    var productId = currentElement.parentElement.parentElement.childElements[0].value;
    console.log(productId);
});

forEach iterates over each element of the array-like object and for each element (stored in currentElement) will execute the callback.

答案 1 :(得分:2)

You did some errors there:

  • document.getElementsByClassName returns multiple elements
  • .onClick(...) is not the way to add an onclick handler

This snippet will remove the parenting <tr> element on click of a Remove-button:

var items = document.getElementsByClassName('remove-item');
for(var i = 0; i < items.length; i++)
{
  var item = items[i];
  item.onclick = function(e)
  {
    e.target.parentNode.parentNode.style.display = "none";
  };
}
<table>
  <tr>
    <td>Test 1</td>
    <td><a href="#" class="remove-item">Remove</a></td>
  </tr>
  <tr>
    <td>Test 2</td>
    <td><a href="#" class="remove-item">Remove</a></td>
  </tr>
  <tr>
    <td>Test 3</td>
    <td><a href="#" class="remove-item">Remove</a></td>
  </tr>
</table>