2016-03-17 36 views
-1

我遇到了addEventListener問題。當我點擊第三個div標籤時,它不會改變背景顏色,並且警報也不起作用。addEventListener不起作用

這裏是我的HTML結構:

<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript" src="myscript.js"></script> 
</head> 
<body> 
    <p>Click the button to display an alert box:</p> 
    <div>Robert</div> 
    <div>Arthur</div> 
    <div>Procedure(Third)</div> 
    <div>Fourth</div> 
    <button onclick="myfunc()">Try it</button> 
</body> 

這裏是JavaScript文件:

var Ar = ["red", "yellow", "green", "blue"] 

function getRandomInt(min, max) 
{ 
    return Math.floor(Math.random() * (max - min + 1)) + min; 
} 

function myfunc() { 
    alert(getRandomInt(0,5)); 

} 

function Group(handler) { 
    var R = []; 
    for (var I = 0, E = document.getElementsByTagName('div'), L = E.length; I < L; I++) { 
     handler && handler.call(E[I]); 
     if (!handler) 
      R.push(E[I]); 
    } 
    return R; 
} 

//get third div tags and set a handler 
Group()[2].addEventListener("click", handler, false); 

function handler() { 
    alert("Test!"); 
    Group()[2].style.backgroundColor = Ar[getRandomInt(0,3)]; 
} 
+0

開始用''的集團()' –

+0

您的代碼console.log'結果[似乎工作(https://jsfiddle.net/fo4kpmt0/)如預期? – Teemu

+0

@Teemu是的,但爲什麼我的電腦在Chrome和Firefox中不起作用?我不明白 – Robert

回答

3

您正在試圖獲取加載之前,他們訪問的元素。

將您的腳本包含在頁面末尾,它將起作用。

<!DOCTYPE html> 
<html> 
<head> 

</head> 
<body> 
    <p>Click the button to display an alert box:</p> 
    <div>Robert</div> 
    <div>Arthur</div> 
    <div>Procedure(Third)</div> 
    <div>Fourth</div> 
    <button onclick="myfunc()">Try it</button> 
</body> 
<script type="text/javascript" src="myscript.js"></script> 
+2

@Robert是的,你可以使用onload,但問題是,它會等待圖像等所有資源加載以發出onload事件。更好的選擇可以是jQuery的Document.ready。 –

3

修改你的代碼。

<body> 
    <p>Click the button to display an alert box:</p> 
    <div>Robert</div> 
    <div>Arthur</div> 
    <div>Procedure(Third)</div> 
    <div>Fourth</div> 
    <button onclick="myfunc()">Try it</button> 
    <script type="text/javascript"> 
     Group()[2].addEventListener("click", handler, false); 
    </script> 
</body> 
相關問題