单击“表格行”更改页面,或打开新选项卡

Table Row onclick - change page, or open new tab

本文关键字:新选项 选项 表格 表格行 单击      更新时间:2023-09-26

我有一个包含行的表,当单击该表时,会将用户带到一个页面,该页面包含有关该行所描述项目的更详细信息。不幸的是,它总是会更改当前页面,我们的用户希望能够用鼠标中键/控制键单击行,以便在需要时打开一个新的选项卡。此选项可用于普通链接,但似乎无法用于我的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>