javascript - jQuery: invoke <a > sub element of table cell - Stack Overflow

admin2025-04-09  0

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

I've tried with

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

An other variants, but to no luck.

--larsw

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

I've tried with

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

An other variants, but to no luck.

--larsw

Share Improve this question asked Dec 29, 2008 at 13:34 larswlarsw 3,8302 gold badges26 silver badges37 bronze badges 1
  • Just a question: why not make the table cell contents the <a> element (display: block)? – cletus Commented Dec 29, 2008 at 13:44
Add a ment  | 

3 Answers 3

Reset to default 5

Why don't you move your JavaScript code out of the href attribute and into your click event? jQuery was made to write unobtrusive JavaScript.

Edit:

No, but really, consider removing 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>
<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>

I have it working fine with that clip above. However see your jQuery selector has a # in front of it , which would be failing unless your table has an id of 'table'.

Having said that, there is probably a better way to do what your after than hidden a tags with javascript embedded in them.

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

$('#table td').click(function() { 
    $(this).find('a').each(function(){ window.location = this.href; });
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744202494a235865.html

最新回复(0)