所以这是我发布的另一个问题的答案,我认为这是正确的解决方案。但是,虽然它在 jsfiddle 中运行良好,但在该环境之外却无法正常运行。我尝试了多种组合,但我无法使它正常工作。
我已经在正文中尝试了 onLoad
,在 header 中尝试了 Window.onload
围绕函数并在所有操作之后在页面底部单独调用它元素已加载。什么都没用。
我总是遇到这个问题:
Uncaught TypeError: Cannot call method 'addEventListener' of null
这令人沮丧,因为我见过的所有其他解决此错误的方法都围绕着确保您确实具有处理程序在 HTML 中触发的指定 ID。我做的。
我知道在这里发帖可能有点矫枉过正,但我急于求成。
这是 JSfiddle:http://jsfiddle.net/fFW5r/1/
这是我为测试这个概念而制作的模型页面(永远行不通):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var link_container = document.getElementById('links');
function myFunction(){ link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
</head>
<body onload="myFunction()">
<div id="links">
<a href="http://fiddle.jshell.net/#foo">Inbound Link</a>
<a href="http://stackoverflow.com">Outbout Link</a>
</div>
<script>window.onload=myFunction()</script>
</body>
</html>
这个特定的迭代我试图在所有内容加载后通过页面底部的 onload
调用对其进行测试。
最佳答案
var link_container = document.getElementById('links');
需要在 document.onload
上执行,所以它必须在 myFunction
在jsfiddle中,代码默认在load
时执行。在左侧面板的 fiddle > 第二个选择框中,如果您选择 no wrap - in head
您可以重新创建问题。
演示:Fiddle
<script type="text/javascript">
function myFunction(){
var link_container = document.getElementById('links'); // <<-- Move it inside `myFunction()`
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
关于Javascript:事件处理程序不工作,在 JSFiddle 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15300074/