Pro*_*ter 6 html javascript onclick href
我有一个包含行的表,在单击时,将用户带到一个页面,其中包含有关该行描述的项目的更多详细信息.不幸的是,它总是会更改当前页面,我们的用户希望能够使用鼠标中键/控件单击行,以便在需要时打开新选项卡.这个选择适用于普通链接,但似乎没有我的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>
Run Code Online (Sandbox Code Playgroud)
使用onclick事件模拟普通链接的最佳方法是什么,因此不同操作系统/浏览器的行为将是相同的,我认为这对于触发在新选项卡中打开链接的内容具有不同的绑定.
我只是偶然发现这个问题,因为我也在寻找解决方案。这是一个可能的解决方案。正常单击时,它会正常打开页面;如果使用中间按钮,它会在新选项卡中打开页面。
您可以添加表类(例如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>
Run Code Online (Sandbox Code Playgroud)