问题
Please I need your help with the code below. I want to add an onclick event to a whole DIV to redirect to an url but I cannot bypass the href included in a child anchor inside the DIV.:
i.e. (The goal is to redirect to google.com clicking anywhere on the image or the text):
<html>
<div onclick="location.href='http://www.google.com'">
<div>
<a href="http://en.wikipedia.org/">
<img height="200" width="200" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png">
</a>
Test
</div>
</div>
</html>
This works fine when I use a local URL like 'file:///E:/Documents/Blog/Design/Tmp1.html' (I don't know why). Thank you.
Update: I'm adding the idea behind this request: I need this for the Index section of my blog that Blogger builds with the same routine that it uses for individual posts. In the Index I want that every click in the main Div redirects to the Post, but inside the post a click in the image must goes to the image's href. My idea was that the "onclick" event it's added dinamically to the DIV only for the Index section.
回答1:
If you're intent on doing this inline (not recommend but it's your code), you can add a return false;
to the inner anchor:
<html>
<div onclick="location.href='http://www.google.com'">
<div>
<a href="http://en.wikipedia.org/" onclick="return false;">
<img height="200" width="200" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png">
</a>
Test
</div>
</div>
</html>
Update: based on step 2 of your request (this is a terrible, terrible idea for a number of reasons but it works):
<html>
<div onclick="location.href='http://www.google.com'">
<div>
<a href="http://en.wikipedia.org/" onclick="if ( this.parentElement.parentElement.onclick ) { return false; }" id="demo">
<img height="200" width="200" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png">
</a>
Test
</div>
</div>
</html>
回答2:
Set an onclick handler using javascript. the code would look something like this:
document.getElementById("mydiv").onclick = function(){
// navigate to new page
window.location.href = 'URL';
}
You will need to add an id to your div and pass it properly in the getElementById function.
回答3:
You can also try something like this:
<div onClick="window.open('http://www.google.com','_blank');">
Change _blank with _self if you want it to open in same window.
来源:https://stackoverflow.com/questions/16949731/how-to-redirect-from-div-and-bypass-child-anchor-href