开发者

Enable Open Link in New Tab with Javascript

I want to have a table with clickable rows that upon clicking will redirect to another page. I'm accomplishing this right now with Javascript. However if you right click there's no option to "Open Link in New Tab" presumably because the browser only does this for links? Is there a way to enable this behavior?

Basically I 开发者_JAVA百科want table rows to act like anchor tags.


Have you tried setting the link in each cell? I had a similar problem, when I was trying to make a whole row like a link, I used a link in each data cell:

<td><a class="mylink" href="URL" target="_blank">...</a></td>
...
<style>mylink {display:block; text-decoration:none; color:black;}</style>

This target attribute will work even if JS is disabled.


Here http://jsfiddle.net/mplungjan/v5JrS/ the fiddle does not position the menu but the script does - tested in Fx5 on Mac:

<html>
<head>
<style>
#menu { display:none; position:absolute;border:1px solid red; background-color:grey }
#menuLink { text-decoration:none }
tr { border:1px solid black}
</style>
<script>
window.onload=function() {

  var trs = document.getElementsByTagName("tr");

  for (var i=0,n=trs.length;i<n;i++) {
    trs[i].oncontextmenu=function(e) {
      document.getElementById("menuLink").href=this.cells[0].innerHTML;
      var menu = document.getElementById("menu");
      menu.style.left=(e)?e.pageX:event.clientX;
      menu.style.top=(e)?e.pageY:event.clientY;
      menu.style.display="block";
      return false;
    }
  }
  document.getElementById("menuLink").onclick=function() {
    document.getElementById("menu").style.display="none";
    // the following is not really needed since the target works
    // fine on its own
//    var w=window.open(this.href,this.target);
//    return w?false:true;
  }
}
</script>
</head>
<body>
<table>
    <tr>
        <td>http://www.google.com</td>
    </tr>
    <tr>
        <td>http://www.bing.com</td>
    </tr>
</table>
<div id="menu"><a id="menuLink" target="_blank" href="">Open in new window/tab</a></div>
</body>
</html>


No, there is no way to enable this behavior easily to work on all browsers. What you have to do is manually update the href of your links to point to whatever page you want the user to go to. Note that this required use of anchor (<a>) tags, which may be difficult to do with table cells. Perhaps you can fill the cells with some sort of invisible image or play with CSS.

Look at http://www.webmasterworld.com/forum21/10629.htm - the fourth post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜