Jquery when i click on img it behaves like link (t

2019-07-23 17:26发布

问题:

i have a problem, I got some li, inside them i have a link and an image. What i want is when someone clicks on the image it triggers the link. I cant put the image in a link, don't ask why :)... So basically it looks something like this

<li><a href="somelink">sometext</a><img src=""/></li>
<li><a href="somelink">sometext</a><img src=""/></li>
...

And i was thinking of doing something like this:

$(img).click(function(){
  var link = $(this).prev;
  $(link).trigger('click');
})

I know this is not correct, but i think you got the picture, thanks for your help.

回答1:

$('img').live('click', function () {
    $(this).closest('a').click();
});


回答2:

Don't use jQuery, but simply move the closing </a> tag at the right side of the <img> tag:

<li><a href="somelink">sometext<img src=""/></a></li>
<li><a href="somelink">sometext<img src=""/></a></li>

If you don't want to change the HTML, use:

$('img').click(function(){
    location.href = $(this).prev().attr("href");
});


Code review

  • $(img) - img is not defined. Did you mean: $('img')? (added quotes, using selector img)
  • var link = $(this).prev; - prev is nto a property, but a method. It has to be invoked: var link = $(this).prev()
  • $(link).trigger('click'). Since link is a jQuery object already, it's unnecessary to wrap the object in another jQuery object. Use: link.trigger('click');
  • Flawed logic: .trigger('click') will not cause the page to be followed, because it doesn't trigger the default browser behaviour (following the link), but invokes the click event of the element. Which is not defined.


回答3:

Actually, that looks like it oughta work. Just note that prev is a function.

Alternatively, you could do something like

window.location = link.attr('href');


回答4:

You can probably get away with something like

$(img).click(function()
{   
      var link = $(this).prev();   
      window.location.href = link.attr('href'); 
});


回答5:

you can set a css class for both the anchor link and the image and use a classname selector to hook the click event

$(".myclass").click(function(){ //Do Stuff })