我有这个简单的代码我无法让它工作。
<html>
<head>
<script type="text/javascript">
window.onload = function () {
p = document.getElementById("foo");
p.click = function() { alert(p); };
}
</script>
</head>
<body>
<div id="foo" style="position:relative;width:100px;height:100px;background-color:red;"> </div>
</body>
</html>
Javascript已开启。如果我在函数之后放()我可以自动运行它。但是,onclick仍然没有工作。 Firebug没有显示任何错误。
答案 0 :(得分:2)
我认为你需要为'click'事件添加一个事件处理程序/监听器,而不是只指定'p.click = ...'
你可以试试这个:
function whenLoaded() {
var p = document.getElementById("foo");
p.addEventListener("click", function(){alert(p)}, false);
}
document.addEventListener("DOMContentLoaded", whenLoaded, false);
*注意:附加事件侦听器因浏览器而异,因此您需要使用抽象差异的库... Jquery可以执行此操作,并为此构建Bean(https://github.com/fat/bean)。你还可以查看Dustin Diaz的domReady如果你只是在寻找一个小的跨浏览器DOM加载的事件处理程序类型 - https://github.com/ded/domready
答案 1 :(得分:1)
p.onclick = function() { alert(p); };
和...记得在创建新var时使用var
var p = document.getElementById("foo");
答案 2 :(得分:1)
请按以下方式更新。尝试。
p.onclick = function() { alert(p); };
答案 3 :(得分:0)
如果您使用jQuery,请尝试以下操作:
$(document).ready(function() {
p = document.getElementById("foo");
$(p).click(function(){
alert(p);
});
});