2013-07-24 28 views
-2

在下面這行中:第三個參數保持爲假。 這個屬性是什麼?在addEventListener中爲false?

var el = document.getElementById("outside"); 
el.addEventListener("click", modifyText, false); 
+3

之證件目的是爲了回答這些問題,你..如果在情況下,它失敗了,這樣的問題就不會得到下票它變得。 – dbf

回答

2

這就是useCapture參數。從documentation

useCaptureOptional

If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. If not specified, useCapture defaults to false.

瞭解更多關於這個話題here

+0

爲什麼你推薦使用jQuery函數?它的行爲與將useCapture設置爲true或false相比如何? – Quentin

+0

@Quentin謝謝你的觀點。更新了答案。 –

+0

你錯了。 'return false;'在jQuery中更像'stopPropagation'和'preventDefault'。它與'useCapture'無關。 – Quentin

0

this文檔,它的羯羊或不使用「捕獲」

If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. If not specified, useCapture defaults to false. Note: useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide this parameter for broadest compatibility.

2

如果事件會冒泡向上或向下的DOM樹它控制。

點擊下面例子中的three(和linked here)。然後將false更改爲true並重復。

如果useCapture設置爲false,它會冒泡的樹,你會得到x3, x2, x1,如果它被設置爲true,它將泡下來,你會得到x1, x2, x3

參見:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
</head> 
<body> 
    <div id="x1">One 
    <div id="x2">Two 
     <div id="x3">Three 
     </div> 
    </div> 
    </div> 
    <script> 
    function me() { alert(this.id); }; 
    var divs = document.getElementsByTagName('div'); 
    for (var i = 0; i < divs.length; i++) { 
     divs[i].addEventListener('click', me, false); 
    } 
    </script> 
</body> 
</html>