I wrote it in a separate js file and used window.onload=function(){} to prevent loading problems
1. Insert the code directly from the body and it works;
2. From Inserting a js file into the body will not work; deleting window.onload=function(){} from the file will work;
3. If written in the head, it will not work whether directly inserting code or files;
4. The console reports no error and the js file can be found in the debugger.
I think there is a problem with page loading. I can’t tell what the specific problem is. . .
Post the code
图片库
我的图片库
百度一下你就知道 封面:
The js code is like this
window.onload=function(){ function showPic(whichpic){ var source=whichpic.getAttribute('href'); var place_holder=document.getElementById('placeholder'); place_holder.src=source; var p=document.getElementById("alt"); var text=whichpic.getAttribute('title'); p.firstChild.nodeValue=text; } var lis=document.getElementsByTagName('a'); for(i=0;i
First of all, I would like to make a suggestion: it is best not to include Chinese characters in file naming, and generally do not start with numbers. There are many naming standards that you can look for yourself.
About the question:
控制台没报错且能在调试器中找到这个js文件
:只要你使用了window.onload=function(){}
, the js code will definitely be executed. No matter whether you put it in the head or the body, or whether you introduce it in the form of a file, the code inside will be executed.从body里插入js文件,不能用;文件中删掉window.onload=function(){},能用
:html中的onclick="showPic(this)"
,这个showPic函数是定义在全局作用域下面的,不能用window.onload包裹,当你包裹的时候,showPic的作用域就处于onload这个函数里面了,在全局作用域下找不到showPic,所以点击时,showPic函数里面的代码没有执行
, other js codes are executed. Look at the a tag, onclick and other codes have been added.写在head里,无论直接插入代码还是文件,都不能用
: When it comes to dom query, the dom tree has not been built yet, so the a tag cannot be queried. The DOM query js code written in the head must be wrapped with window.onload, but you must extract the showPic function and place it in the global scope so that it can run normally.@张东东 The answer is correct, but he used the element.onclick binding event method (the code you commented out). At this time, the showPic function can be found in the scope chain, so it can be executed.
@stephenhuang Can the showPic code written in onload run?
script should be placed under the body
The first thing you need to know is:
html files are executed in a top-down manner, but the order of the introduced css and javascript is different. When the css is introduced and loaded, the program is still executed downwards, and when the