Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
直接从html调用javascript方法_Javascript_Html_Jsp - Fatal编程技术网

直接从html调用javascript方法

直接从html调用javascript方法,javascript,html,jsp,Javascript,Html,Jsp,您好,我想直接从jsp调用javascript方法。下面是这个javascript方法中的伪代码print1()没有调用 <html>` <body> <h1>hello</h1> <script>print1()</script> <p>hii</p> <script> function print1(){ alert("hello"); docume

您好,我想直接从jsp调用javascript方法。下面是这个javascript方法中的伪代码print1()没有调用

<html>`
 <body>
 <h1>hello</h1>
 <script>print1()</script>
 <p>hii</p>

  <script>
   function print1(){
    alert("hello");
    document.getElementsByTagName("p").innerHTML="hey";
    }
   </script>
   </body>
   </html>
`
你好
print1()
hii

函数print1(){ 警惕(“你好”); document.getElementsByTagName(“p”).innerHTML=“嘿”; }
解决这个问题可以在很大程度上帮助我。
注意:我不能使用onload调用它,因为这只是一个伪代码,我必须将逻辑应用到其他一些代码中。有两个选项可以解决此问题:

选项1:将调用
print1()
移动到文件的末尾(即,在调用之前首先定义函数,并寻找关于此的清晰解释)

选项2:在
主体
加载时调用它,如下所示:

<body onload="print1()">

</body>

首先,代码中有一些语法错误需要修复

然后,您需要在定义函数后(或在相同的
标记中)调用该函数。未及时提升
print1()
。这是因为浏览器一遇到脚本就试图执行它。这意味着当浏览器看到
print1()
时,它甚至不知道文件的其余部分

因此,需要在定义函数后调用print1()。除了注释和其他答案中的解决方案外,另一个选项是将脚本放在单独的文件中,并使用
defer
调用它

printFunc.js:

print1();
在html文件中:

<script src="printFunc.js" defer></script>

首先,您可以在body标记中将其称为“onload”,其次,“getElementsByTagName”返回数组,所以您必须知道要在哪个数组位置进行更改

 <html>`
 <body onload= "print1()">
  <h1>hello</h1>


    <p>hii</p>

  <script>
    function print1(){
     alert("hello");
      document.getElementsByTagName("p")[0].innerHTML="hey";
     }
   </script>
`
你好
hii

函数print1(){ 警惕(“你好”); document.getElementsByTagName(“p”)[0].innerHTML=“嘿”; }

你也可以这样做

 <html>`
   <body>
    <h1>hello</h1>

      <p>hii</p>

    <script>
     function print1(){
       alert("hello");
        document.getElementsByTagName("p")[0].innerHTML="hey";
       }
   </script>
   <script>print1();</script>
   </body>
    </html>
`
你好
hii

函数print1(){ 警惕(“你好”); document.getElementsByTagName(“p”)[0].innerHTML=“嘿”; } print1();
您的代码有一些错误。你需要在“嘿”之后关闭报价单。在标记后还有一个字符,请将其删除。将
print1()
添加到脚本末尾(就在
之前)。您的主要问题是在定义它之前调用
print1()
。交换这两个脚本,它就会工作(在您修复上述语法错误之后)。由于函数提升,不会在当前仍然工作的地方编写print1()。@AnanthRao不在两个脚本块中。
 <html>`
   <body>
    <h1>hello</h1>

      <p>hii</p>

    <script>
     function print1(){
       alert("hello");
        document.getElementsByTagName("p")[0].innerHTML="hey";
       }
   </script>
   <script>print1();</script>
   </body>
    </html>