开发者

jQuery div onclick to click an href inside the div

I have the following HTML:

<table class="products">
  <tr>
开发者_运维技巧    <td>Product description probably goes here</td>
    <td><a href="#">more information</a></td>
  </tr>
</table>

To make it a bit sexier for Javascript-enabled browsers I've added this jQuery (1.3.2):

$(document).ready(function(){
  $('table.products tr').click(function(){
    $(this).find('a').click();
    return false;
  });
});

But I think it gets into an infinite loop or something. Safari shows this:

RangeError: Maximum call stack size exceeded. jquery.min.js:12

Can anyone please offer a workaround or better way?


The problem here is that a lies within the tr. Ergo, when the a click() method is triggered, the event bubbles to the tr containing it, creating the recursive loop you mentioned. Rather than call .find('a').click(), have both a and tr use the same click method.

$('tr, a').click(function(){
   //dostuff
   return false;
});


I had the same problem and I solved it with adding e.stopPropagation(); to the a on click:

$(document).ready(function() {
  $('table.products tr').bind('click', function() {
    $(this).find('a').click();
    return false;
  });

  $('table.products tr a').bind('click', function(e) {
    e.stopPropagation();
  });
});


This is a pretty late answer, but I found this to be a very short and simple solution:

$('ul li').bind('click', function() {
    location = $(this).find('a').attr('href');
});


Simply try to use bind('click') instead of click() shortcut, it worked for me in almost same case.


First, I would console.log($(this).find('a')) and make sure it is the appropriate link. Next, I believe the click event is not what you want on the a element. I think you just want: var a = $(this).find('a'); if (a) document.location.href = a.attr('href');

My JavaScript is pretty weak though : )


mine was a list item in a dropdown so i wanted the event to keep bubbling so the dropdown would be closed. this is the solution i used:

$('div#outer').click(function (e) {
   if (e.target == e.currentTarget) // prevents bubbled events from triggering
      $($(e.currentTarget).children()[0]).trigger('click');
});


$(document).ready(function(){
  $('table.products tr').click(function(e){
    e.stoPropagation(); // for stop the click action (event)
    $(this).find('a').click();
    return false;
  });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜