单击“表格行”更改页面,或打开新选项卡
Table Row onclick - change page, or open new tab
我有一个包含行的表,当单击该表时,会将用户带到一个页面,该页面包含有关该行所描述项目的更详细信息。不幸的是,它总是会更改当前页面,我们的用户希望能够用鼠标中键/控制键单击行,以便在需要时打开一个新的选项卡。此选项可用于普通链接,但似乎无法用于我的onclick。示例如下:
<html>
<body>
<table border='1'>
<tr onclick='window.open("http://www.google.com")'>
<td>Open Another Window</td>
</tr>
<tr onclick='location.href="http://www.google.com"'>
<td>Change Current Page</td>
</tr>
</table>
</body>
</html>
用onclick事件模拟正常链接的最佳方法是什么,这样不同的操作系统/浏览器的行为就会相同,我相信它们对触发在新选项卡中打开链接的触发因素有不同的绑定。
这对我有效:
<tr onclick="window.open('http://www.google.com','_blank')">
我只是偶然发现了这个问题,因为我也在寻找解决方案。这里有一个可能的解决方案。它在正常单击时正常打开页面,如果使用中间按钮,则在新选项卡中打开页面。
您可以添加一个表类(如clickable-rows
)来轻松地将这种行为应用于表。然后添加带有链接的数据属性(如data-href
)。
<!DOCTYPE html>
<html>
<body>
<table>
<tr class="clickable-row" data-href="http://www.google.com">
<td>Clickable row 1</td>
</tr>
<tr data-href="http://www.google.com">
<td>Non clickable row</td>
</tr>
<tr class="clickable-row" data-href="http://www.google.com">
<td>Clickable row 2</td>
</tr>
</table>
<script>
// loop through the table rows with the clickable-row class, and turn them into clickable rows by
// setting the cursor to a pointer, and adding a mousedown listener to open in the current page
// if left-clicked, or open in a new tab if middle-clicked
let rows = document.querySelectorAll("tr.clickable-row");
rows.forEach((clickableRow) => {
clickableRow.style.cursor = "pointer";
clickableRow.addEventListener("mousedown", function(e) {
e.preventDefault();
var href = this.getAttribute('data-href');
if (e.button === 1)
{
window.open(href, "_blank");
}
else if (e.button === 0)
{
window.location = href;
}
})
});
</script>
</body>
</html>
不要处理表行的点击事件,而是使用锚标记。Ctrl+单击锚点的默认行为是在新窗口或选项卡的href属性中打开URL。如果您希望在不使用Ctrl按钮的情况下打开新选项卡或窗口,也可以使用锚点的target属性。
<td><a href="http://www.google.com" target="_blank">open another window or tab</a></td>
<tr onclick="window.open('./putyourlink.php')"> it's still work to me also but pls put '_blank' like another answer it's good more </tr>
相关文章:
- 如何通过Primefaces3.5使用JSF2.0验证并在成功的情况下打开一个新的选项卡
- 打开一个新的选项卡/窗口并向其写入内容
- 使用 POST 打开新的选项卡或窗口 [PHP]
- 提交表单后,打开一个新的选项卡
- 使用javascript打开一个新的选项卡,但使用javascript保留在当前选项卡上
- 如何通过单击Highchart图中的列/栏打开新窗口/选项卡
- JavaScript在新的选项卡中打开,而不是在Chrome浏览器中打开窗口
- Javascript表单提交打开新窗口选项卡,然后重定向父页面
- 在 CSS 中使用新的选项和样式
- 来自 HREF 的新窗口/选项卡
- 将表单提交到新窗口/选项卡
- 如何在新窗口/选项卡中打开文本和 xml 文件
- 检测链接是在新窗口/选项卡还是当前窗口中打开
- 新窗口/选项卡中的JavaScript确认对话框
- Angular:打开新的选项卡,不使用弹出窗口阻止程序
- 为什么打开的窗口有时打开一个新的选项卡,有时弹出
- 如何打开新窗口/选项卡,但专注于打开窗口
- 在磁盘上的新浏览器选项卡中使用javascript以编程方式打开html文件
- 如何通过javaScript获取新打开选项卡的URL
- 打开一个新的选项卡,并使用javascript用父页面的innerHTML填充页面