JQuery: invoke <a} table cell subelement

Is it possible to add a jQuery function so that a click in a table cell invokes a hidden <a href = "javascript: ..." /> element (ie, a descendant of TD)?

I tried with

$ ('# table td'). click (function () {. $ (This) .find ('a') click ();});

Other options but no luck.

- larsw

+1


source to share


3 answers


<html>
<head></head>
<body>
<table border=1>
    <tr>
        <td>a1<a href=# onclick='alert("a1")' /></td>
        <td>a2<a href=# onclick='alert("a2")' /></td>
    </tr>
    <tr>
        <td>b1<a href=# onclick='alert("b1")' /></td>
        <td>b2<a href=# onclick='alert("b2")' /></td>
    </tr>
</table>
<script src="scripts/jquery-1.2.6.min.js" ></script>
<script>
    $(function(){
        $('table td').click(function(){ $(this).find('a').click()});
    })
</script>
</body>
</html>

      

It works fine for me with this clip above. However, see that your jQuery selector has a # in front of it, which will fail if your table doesn't have a "table" id.



Having said that, there is probably a better way to do what's yours than hidden tags with inline javascript.

+2


source


Why don't you move the JavaScript code out of the attribute href

and into the click event? jQuery was made for writing unobtrusive JavaScript.

Edit:

No, but really, remove those hidden links in favor of unobtrusive JavaScript. Here are the relevant parts of Corey's example, rewritten:

JS:



  $(document).ready(function() {
    $('table td').click(function(event) {
      alert($(this).html())
    })
  })

      

HTML:

<table border="1">
  <tr>
    <td>a1</td>
    <td>a2</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
  </tr>
</table>

      

+5


source


This would be a workaround if you want to avoid adding onclick:

$('#table td').click(function() { 
    $(this).find('a').each(function(){ window.location = this.href; });
});

      

+1


source







All Articles