2011-08-08 82 views
2

我試着通過目前通過一些代碼跟蹤學習JavaScript,我想知道是否有人能解釋什麼是這個代碼片段發生(此代碼段僅僅是一個函數,因此沒有大括號的部分):有人可以解釋這段代碼正在做什麼?

document.addEventListener("keydown",function(e){ 

     for(i=0;i < keys.length; i++) { 

      if(e.keyCode == keys[i]){ 

      var tri = document.getElementById("foo").childNodes[i]; 

      if(i==0){ 
       var tri = document.getElementById("foo").childNodes[1]; 
      } 

      if(i==1){ 
       var tri = document.getElementById("foo").childNodes[3]; 
      } 

      if(i > 1) { 
       var tri = document.getElementById("foo").childNodes[(i*2)+1]; 
      } 

im在這裏最困惑的部分是childNodes []和if(i)語句嗎?

+0

將導致丟失關閉大括號的語法錯誤 – Ibu

+0

@Ibu - 顯然這個片段不包含整個方法 –

回答

3
// Bind an event handler to keydown on the entire document 
document.addEventListener("keydown",function(e){ 

    // Everything in here happens on keydown 

    // keys must be an array declared somewhere earlier in the code 
    // This loops through that array 
    for(i=0;i < keys.length; i++) { 

     // If the current key we are looking at in the array 
     // is the key that was pressed 
     if(e.keyCode == keys[i]){ 

      // Get the (i+1)th childnode of foo 
      var tri = document.getElementById("foo").childNodes[i]; 

      // If i = 0 get the second element (not the first) 
      if(i==0){ 
       var tri = document.getElementById("foo").childNodes[1]; 
      } 

      // If i == 1 get the fourth element (not the second) 
      if(i==1){ 
       var tri = document.getElementById("foo").childNodes[3]; 
      } 

      // Otherwise get the (i*2+2)th element. 
      if(i > 1) { 
       var tri = document.getElementById("foo").childNodes[(i*2)+1]; 
      } 

      // Here we are still in an if-statement, in a loop, in a function, 
      // so there is probably more code here, at least some closing }'s 

注意var tri = document.getElementById("foo").childNodes[i];是一個無用的線,因爲i不能爲負,接下來的三個之一,如果語句總是會成功,tri將被覆蓋。

還要注意的是,當i = 0(i*2)+1 = 1i = 1(i*2)+1 = 3,所以與其他兩個if語句是無用的,以及因爲第三覆蓋了所有的情況下,並不需要甚至是如果子句。上面的代碼是100%等同於:

document.addEventListener("keydown",function(e){ 

    for(i=0;i < keys.length; i++) { 

     if(e.keyCode == keys[i]){ 

      var tri = document.getElementById("foo").childNodes[(i*2)+1]; 

      ... 

i由於是稱爲keys用於通過數組迭代變量,和所選擇的節點取決於ikeys必須是一個具有不尋常目的的數組。它是一個keyCodes數組,其中keyCode在數組中的位置確定在按下該鍵時應該選擇並存儲在tri中的哪個節點。

0

它根據被按下的鍵獲取不同的DOM元素。

1

Childnodes是DOM元素的後代的集合(有效地)。

E.g.考慮一些標記:

<div id='div1'> 
    <p id='p1'> 
     <span id='s1'>Span one</span> 
     <span id='s2'>Span two</span> 
     <span id='s3'>Span three</span> 
    </p> 
</div> 

在這種情況下,的document.getElementById( 'P1')的childNodes [0]將返回跨度使用id = 'S1',的childNodes [1]將返回跨度使用id =」 s2'等。

http://www.w3schools.com/Dom/prop_element_childnodes.asp

更多細節:https://developer.mozilla.org/En/DOM/Node.childNodes

人們會抱怨鏈接w3schools.com,但恕我直言它是足夠快片頭概念。

相關問題