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

Is it possible to add a jQuery function so that a click in a table cell will invokea hidden <a href=

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; });
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744202493a4562946.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信