kitz kitz - 6 months ago 26
HTML Question

Clickable table row

I have this structure:



jQuery('tr').bind('click', function() {
var p = jQuery(this);
p.children('td').children('a').click();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="88">A</td>
<td width="88">B</td>
<td width="88">C</td>
<td width="88">D</td>
<td width="88">E</td>
<td width="88">F</td>
<td width="88">G</td>
</tr>
<tr>
<td align="right">content A1</td>
<td align="right">content B1</td>
<td align="right">content C1</td>
<td align="right">content D1</td>
<td align="right">content E1</td>
<td>content F1</td>
<td>
<a href="http://google.com" target="_blank">google</a>
</td>
</tr>
<tr>
<td align="right">content A2</td>
<td align="right">content B2</td>
<td align="right">content C2</td>
<td align="right">content D2</td>
<td align="right">content E2</td>
<td>content F2</td>
<td>
<a href="http://facebook.com" target="_blank">facebook</a>
</td>
</tr>
</tbody>
</table>





I want to programmatically call the click on
<a>
tag when I click on the table line.

Till now my code runs in a stack overflow error:

Uncaught RangeError: Maximum call stack size exceeded


P.S. In my real code the
a
tag looks like this:

<a href="image_url" data-lightbox="image-1">
<img src="thumb_image_url" />
</a>


and click on the image starts a lightbox effect.

Answer

I tried with pure javascript solution. It's working

//jQuery('tr').bind('click', function() {
//  var p = jQuery(this);
//  p.children('td').children('a').click();
//});

var tr = document.querySelectorAll('tr');

if (tr) {
  for (var i = 0; i < tr.length; i++) {
    var element = tr[i];
    element.addEventListener('click', clickedTr, false);
  }
}

function clickedTr() {
  var td_a = this.querySelectorAll('td a');
  if (td_a) {
    for (var i = 0; i < td_a.length; i++) {
      alert(td_a[i]);
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0">
  <tbody>
    <tr>
      <td width="88">A</td>
      <td width="88">B</td>
      <td width="88">C</td>
      <td width="88">D</td>
      <td width="88">E</td>
      <td width="88">F</td>
      <td width="88">G</td>
    </tr>
    <tr>
      <td align="right">content A1</td>
      <td align="right">content B1</td>
      <td align="right">content C1</td>
      <td align="right">content D1</td>
      <td align="right">content E1</td>
      <td>content F1</td>
      <td>
        <a href="http://google.com" target="_blank">google</a>
      </td>
    </tr>
    <tr>
      <td align="right">content A2</td>
      <td align="right">content B2</td>
      <td align="right">content C2</td>
      <td align="right">content D2</td>
      <td align="right">content E2</td>
      <td>content F2</td>
      <td>
        <a href="http://facebook.com" target="_blank">facebook</a>
      </td>
    </tr>
  </tbody>
</table>