如何把JS里的onmouseover事件不写到<head>里
补充:<html>
<head>
<script type="text/javascript">
function mouseOver()
{
document.getElementById('b1').src ="/i/eg_mouse.jpg"
}
function mouseOut()
{
document.getElementById('b1').src ="/i/eg_mouse2.jpg"
}
</script>
</head>
<body>
<a href=>http://www.w3school.com.cn" onmouseover="mouseOver()" onmouseout="mouseOut()">
<img alt="Visit W3School!" src="/i/eg_mouse2.jpg" id="b1" />
</a>
</body>
</html>
这是一段w3cshool里的代码
我如果要把<head>里的JS代码写到onmouseover里该怎么写?
补充1:没办法写在<head>里也没办法写在外部文件,只能写在<body>里。
答案:方法一:
最直接的写在body里,js可以写在页面的任何位置。
<html>
<head>
</head>
<body>
<script type="text/javascript">
function mouseOver()
{
document.getElementById('b1').src ="/i/eg_mouse.jpg"
}
function mouseOut()
{
document.getElementById('b1').src ="/i/eg_mouse2.jpg"
}
</script>
<a href=>http://www.w3school.com.cn" onmouseover="mouseOver()" onmouseout="mouseOut()">
<img alt="Visit W3School!" src="/i/eg_mouse2.jpg" id="b1" />
</a>
</body>
</html>
----------------------------------------------------------------------------------
方法二:
鉴于你的函数代码都很少,可以直接写在onmouseover里。
<html>
<head>
</head>
<body>
<a href=>http://www.w3school.com.cn" onmouseover="javascript:document.getElementById('b1').src='/i/eg_mouse.jpg';" onmouseout="document.getElementById('b1').src ='/i/eg_mouse2.jpg'">
<img alt="Visit W3School!" src="/i/eg_mouse2.jpg" id="b1" />
</a>
</body>
</html>
其他:可以把脚本写在外部,然后在本页中调用即可。 为什么不能写在外部文件、 你可以这样做 写在外部文件,加上一句,document.getElementById('你要绑定的元素').onmouseover=mouseOver();
在网页引用的时候把<script type='text/javascript' src='....'></script>写到body里面
我也是一知半解 应该还有其它方法更好的方法,用了jquery我就在想他是怎么绑定事件的
上一个:js中怎样把下面的代码用循环写出来?
下一个:js验证表单网址