简体   繁体   English

onload属性在jsp中不起作用

[英]onload attribute doesn't work in jsp

I'm executing an internal script (and external scripts), using <script> inside <head> . 我正在使用<head>内的<head> <script>执行内部脚本(和外部脚本)。

I'd like to execute some JavaScript after the document has been "loaded". 我想在文档“加载”后执行一些JavaScript。

I put a "onload" attribute inside the body : 我在体内放置了“ onload”属性:

<body onload="myFunctionName();">

I call the function with the "onchange" attribute inside the jsp (inside <html:select ... > struts tag) : 我在jsp(在<html:select ... > struts标记内)的“ onchange”属性中调用该函数:

onchange="javascript:myFunctionName();" 

The "onchange" attribute works but not the "onload" attribute. “ onchange”属性有效,但“ onload”属性无效。 Why ? 为什么呢

My code is working here ! 我的代码在这里工作!

<!DOCTYPE html>
<html>
    <head>
        <title>My Title</title>
    </head>
    <body onload="myFunctionName();">

    </body>
</html>
<script type="text/javascript">

   function myFunctionName(){
        alert('I am here!');
    }

    myFunctionName();

</script>

You can try this 你可以试试这个

 <!DOCTYPE html> <html> <head> <title>My Title</title> </head> <body onload="myFunctionName();"> </body> </html> <script type="text/javascript"> function myFunctionName(){ alert('I am myFunctionName!'); } </script> 

But good practice is to separate javascript from html. 但是好的做法是将javascript与html分开。

It doesn't work because HTML 5 doesn't support the onload attribute. 它不起作用,因为HTML 5不支持onload属性。 ( <!doctype html> ) I use a shortcut <!doctype html> )我使用快捷方式

by detecting an error of an image. 通过检测图像错误。 Here is an example that you can just copy&paste: 这是一个您可以复制并粘贴的示例:

 <!doctype html> <html> <head> <title>Your Title</title> <head> <body> <img src="noSrc" alt="" onerror="myFunction()"> <!--This img tag and all the attributes are mandatory or else it will not work--> <script> function myFunction() { //code here document.write("Document Loaded."); //example window.alert("Document Loaded"); } </script> </body> </html> 

Good Luck!! 祝好运!!

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

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