简体   繁体   English

链接元素中的HTML onload事件不起作用

[英]HTML onload Event in link element doesn't work

Based on w3schools, HTML onload attribute supports link tag so I'm trying to load a javascript function when the link is loaded. 基于w3schools,HTML onload属性支持链接标记,因此我在加载链接时尝试加载javascript函数。 The problem is the onload attribute won't fire the function. 问题是onload属性不会触发该函数。 There's no errors. 没有错误。 Why is this? 为什么是这样? I'm sorry for noob question. 对于菜鸟问题​​,我感到抱歉。

I tried using onload in body and it works. 我尝试在身体上使用onload,并且有效。 But when I try to use onload in link tags like link or a tags it doesn't work. 但是,当我尝试在链接标签(例如link或标签)中使用onload时,它不起作用。

    <a onload='myFunction("Hello");'> Test <a>

    <script type="text/javascript">
    function myFunction(value){
    console.log(value);
    }
    </script>

I need to run a function after the link loads. 链接加载后,我需要运行一个函数。 In this example, it should print "Hello" in console. 在此示例中,它将在控制台中打印“ Hello”。

a tag hasn't got a onload property. 标签没有onload属性。 See the link in my comments. 请参阅我评论中的链接。

The onload event is fired just on these elements:  
   <body>, <frame>, <iframe>,
 <img>, <input type="image">,
 <link>, <script>, and <style>

Based on https://www.w3schools.com/tags/ev_onload.asp onload event attribute can be used with tags: 基于https://www.w3schools.com/tags/ev_onload.asp,onload事件属性可以与标签一起使用:

<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>

You are NOT using <link> tag. 没有使用<link>标记。 You are using anchor( <a> ) tag on which this attribute is not supported! 您正在使用不支持该属性的anchor( <a> )标记! <link> tag is used to link an external resource to the document. <link>标记用于将外部资源链接到文档。 For example CSS file. 例如CSS文件。

<head>
  <link rel="stylesheet" type="text/css" href="theme.css">
</head>

onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). 一旦网页完全加载了所有内容(包括图像,脚本文件,CSS文件等), onload最常在元素内用于执行脚本。 However, it can be used on other elements as well (see "Supported HTML tags" below). 但是,它也可以在其他元素上使用(请参见下面的“支持的HTML标签”)。

Supported HTML tags: <body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>

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

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