开发者

Click all but one element in a container to link

So in...

<div id="a">
     <img src="/foo/bar.jpg">
</div>

I want to be able to click everywhere inside of the div EXCEPT for on the image...

$(document).ready(function(){
      // Somehow select id A but not the image here?!
      $("#a").click(function(){
           window.location = '开发者_如何学Gohttp://google.com';
      });
 });

Is this possible?

I tried using .not() and :not(), but could not figure it out...Any thoughts?


See jQuery.is documentation. You can check which element was clicked from the event.target

$("#a").click(function(e){
    if(!$(e.target).is('img'))
       window.location = 'http://google.com';
});

Fiddle


Events are triggered on all parent elements of the element where it originated. You need to check which element triggered the event:

$(document).ready(function(){
    $("#a").click(function(e){
        if (e.target.nodeName.toLowerCase() !== 'img') {
            window.location = 'http://google.com';
        }
    });
});


Try something like this:

<div style="position:relative;width:100px;height:100px">
    <a style="display:block;width:100px;height:100px;position:absolute;top:0px;left:0px" href="http://google.de">Google</a>
    <img src="/foo/bar.png" style="position:absolute;top:10px;left:10px" />
</div>


Need to look at event.target Wrote an example here at JSBIN

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜