Javascript 如何在更改父窗口的同时单击链接以在新窗口中打开 PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11848434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:21:40  来源:igfitidea点击:

How to click on a link to open a PDF in a new window while at the same time changing the parent window?

javascripthtml

提问by Ron Wright

How to click on a link to open a PDF in a new window while at the same time changing the parent window?

如何在更改父窗口的同时单击链接以在新窗口中打开 PDF?

Something like? …

就像是?…

<a href="assets/pdf/a_pdf_doc.pdf" target="new"
   onclick="window.parent.location.href='newpage.html';">A PDF Doc</a>

Of course the above doesn't work....just an example of what I perceive to be close to the answer. Thanks!

当然,以上不起作用......只是我认为接近答案的一个例子。谢谢!

回答by C???

You could move the "new window" and the "redirect" functionality into a single JS function. Here's what that definition might look like:

您可以将“新窗口”和“重定向”功能移动到单个 JS 函数中。该定义可能如下所示:

<script type="text/javascript">

    function openPdf(e, path, redirect) {
        // stop the browser from going to the href
        e = e || window.event; // for IE
        e.preventDefault(); 

        // launch a new window with your PDF
        window.open(path, 'somename', ... /* options */);

        // redirect current page to new location
        window.location = redirect;
    }

</script>

And then in your HTML:

然后在你的 HTML 中:

<a href="assets/pdf/a_pdf_doc.pdf"
    onclick="openPdf(event, 'assets/pdf/a_pdf_doc.pdf', 'newpage.html');">
    A PDF Doc
</a>

I would keep the regular hrefattribute specified in case a user has JS turned off.

href如果用户关闭了 JS,我会保留指定的常规属性。

回答by Losbear

try changing the link to:

尝试将链接更改为:

<a href="javascript:void(0)" onclick="opentwowindows()">click me</a>

and then create a javascript function the current page and the parent page; something like:

然后为当前页面和父页面创建一个javascript函数;就像是:

<script>

function opentwowindows() {
       window.parent.location.href='newpage.html';
       window.location.href="/anotherpage.html';
 }

</script>