我是一个js新手,我正在尝试掌握内联与传统注册。代码块1(内联)工作正常,但代码块2(传统)不行。有人能指出我的错误吗?
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
</script>
</head>
<body>
<input type="button" onclick="gethash()" value="Get your hash" />
</body>
</html>这种使用传统注册的尝试不起作用:
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
document.getElementById('myname').onclick = gethash;
</script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />
</body>
</html>发布于 2012-07-03 06:38:36
在尝试使用onclick绑定某些内容时,没有这样的元素。将该行移动到文件的底部。
如果您查看控制台,您应该会看到如下错误:
未捕获TypeError:无法设置null的属性'onclick‘
这应该可以解决这个问题:
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />
<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
document.getElementById('myname').onclick = gethash;
</script>
</body>
</html>这使我们找到了更好的方法来做这件事。使用window.onload,您可以在加载所有内容之后执行JS代码。
window.onload = function() {
document.getElementById('myname').onclick = gethash;
};发布于 2012-07-03 06:41:02
当您调用document.getElementById('myname').onclick = gethash;时,您试图将事件绑定到的元素尚不存在。
您需要将代码放在onload事件中,如下所示:
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
window.onload = function() {
document.getElementById('myname').onclick = gethash;
}
</script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />
</body>
</html>使用onload并不理想,因为它在触发之前等待所有资源加载。使用DOMContentLoaded事件会更好,或者为了实现跨浏览器兼容性,请查看诸如jQuery之类的库。
顺便说一句,将表示和逻辑分开是一个非常好的想法,因此应该避免使用内联事件处理程序。
发布于 2012-07-03 06:45:51
sachleen是正确的(下面的代码是有效的)-尽管你可以简单地将整个javascript代码块移动到body标签的末尾:
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />
<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
document.getElementById('myname').onclick = gethash;
</script>
</body>
</html>https://stackoverflow.com/questions/11302083
复制相似问题