How to redirect from DIV and bypass child anchor href

最后都变了- 提交于 2019-12-05 17:55:10

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>

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!