简体   繁体   English

通过JS转到另一个HTML文件

[英]Go to another html file via JS

I have an 我有一个

<a href= ./index2.html> 

button in my index.html but now I want to change it so it also calls a function when it gets clicked, so I tried 我的index.html中的按钮,但现在我想更改它,以便在单击它时也调用一个函数,所以我尝试了

<a href="./index2.html;javascript:randomFunction();"

but it doesn't work, how can I make an element make switch html page and call a function at once? 但是它不起作用,我如何使一个元素进入html页面并立即调用一个函数? Thanks!! 谢谢!!

Assuming that you want to run the JS on the current page: 假设您要在当前页面上运行JS:

The quick and dirty method that you shouldn't use is to add an onclick attribute. 您不应该使用的快速而肮脏的方法是添加onclick属性。

<a href="index2.html" onclick="randomFunction()">

The clean approach is to bind an event handler with JS. 干净的方法是将事件处理程序与JS 绑定

reference_to_anchor.addEventListener('click', randomFunction);

(See the documentation linked above for details, and for work arounds to lack of support in older versions of IE). (请参阅上面链接的文档,以获取详细信息,以及在较旧版本的IE中缺乏支持的解决方法)。

(See also Progressive Enhancement and Unobtrusive JavaScript ). (另请参见渐进增强功能JavaScript )。

This will run the JavaScript on the page on which the link appears before the link is followed. 这将在跟随链接之前在出现链接的页面上运行JavaScript。

If, on the other hand, you want the JavaScript to run on the destination page: 另一方面,如果您希望JavaScript在目标页面上运行:

You have a rather more complicated problem to deal with. 您有一个比较复杂的问题要处理。

A new page means a new execution environment. 新页面意味着新的执行环境。 Client side code on one page can't trigger client side code on the next. 一页上的客户端代码无法触发下一页上的客户端代码。

I'd approach that problem by having a server side script generate index2 and include <script>randomFunction();</script> if a particular query string was present on the URI. 我由具有服务器侧脚本接近这个问题产生index2和包括<script>randomFunction();</script>如果一个特定的查询字符串是存在于URI。

make it call the desired function via onclick event, at the end of the function do a: 通过onclick事件使其调用所需的函数,在该函数的末尾执行以下操作:

window.location=url;

or if you want to change page and then call a function on the new one use a normal a tag to go to the new page, then: 或者,如果您要更改页面,然后在新的页面上调用一个函数,请使用普通a标签转到新页面,然后:

window.onload=function(){
     //do something
}

You can use onclick="javascript:randomFunction()" 您可以使用onclick="javascript:randomFunction()"

For instance: 例如:

<a href="./index2.html" onclick="randomFunction()">

使用onclick事件来调用函数

<a href="index2.html" onclick="javascript:randomFunction();"></a>

you can use onclick event of javascript. 您可以使用javascript的onclick事件。

<a href="./index2.html" onclick="return randomFunction();"></a> 

function randomFunction(){
   // do needfull code here.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM