简体   繁体   English

为什么在外部文件中使用内联代码不起作用,但在使用函数时起作用

[英]why when using inline code in external file doesn't work, but when using function work

I know the title of question maybe not be understood, but I will explain that. 我知道问题的标题可能无法理解,但我会解释一下。

Everyone know we can use any of the following way. 每个人都知道我们可以使用以下任何一种方式。

Example(1) 例子(1)

document.getElementById('idofelement').onsubmit = function() {
   alert('Go ahead');
   return false;
}

Example(2) 例子(2)

function DisplayMsg(){
   alert('Go ahead');
   return false;
}

// and in HTML
<form action="file.php" method="post" onsubmit="return DisplayMsg();">

My question (1): 我的问题(1):
What is the difference between the two ways or two examples 两种方式或两个示例有什么区别

My question (2) : 我的问题(2):
Why the example (1) not work in external JavaScript file, but work with me when it is inserted near by the target HTML code. 为什么example (1)在外部JavaScript文件中不起作用,但是在目标HTML代码附近插入example (1)时与我一起工作。 While the example (2) work in any place Whether in external file or near by the target HTML code. example (2)可以在任何位置工作,无论是在外部文件中还是在目标HTML代码附近。

You should always call the method getElementById after the document is loaded. 加载文档后,应该始终调用方法getElementById。 So as suggested by @JanDvorak you should wrap that by $.ready() using jQuery. 因此,正如@JanDvorak所建议的那样,您应该使用jQuery将其包装在$.ready()中。 And if you are not, use window.onload = function() instead. 如果不是,请改用window.onload = function()

btw: don't forget semicolon after definition of function, IE is vulnerable to this syntax 顺便说一句:函数定义后不要忘记分号,IE容易受此语法的影响

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

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