2012-01-16 53 views
0

我有UL列表和代碼選擇所選的LI元素(https://stackoverflow.com/a/8883690/106616)的所有父母。現在,我想在選擇其他LI元素時清除選擇。 爲此,我創建了該代碼:jQuery - 奇怪的功能行爲

(簡單地說,在選擇新路徑之前,我遍歷數組以清除之前的選擇,然後清除數組,並選擇新路徑時添加新的物品到該陣列)

$('#nav li').click(function() { 
     //clear the previous selection 
     $.each(myArray, function (i, v) { 
      console.log('loop: ' + v); 
      $('#nav li a[href="' + v + '"]').css('background-color', 'Green'); 
     }); 

     myArray.lenght = 0; 

     //add the new selection 
     $(this).children('a').each(function (item) { 
      myArray.push($(this).attr('href')); 
      console.log('adding: ' + $(this).attr('href')); 
      $(this).css('background-color', 'Red'); 
     }); 
    }); 

但是,如果我選擇第一個路徑,該代碼會生成該輸出。

加入:#/ 1210

循環:#/ 1210

加入:#/ 1209

循環:#/ 1210

循環:#/ 1209

加入:#/ 1208

如果我選擇例如第二路徑,輸出是:

循環:#/ 1210

循環:#/ 1209

循環:#/ 1208

加入:#/ 1188

環:#/ 1210

loop:#/ 1209

循環:#/ 1208

循環:#/ 1188

加入:#/ 1187

我覺得輸出應爲(第2路徑選擇)

循環: #/ 1210

循環:#/ 1209

循環:#/ 1208

加入:#/ 1188

加入:#/ 1187

有人可以解釋這對我?

+1

到底是什麼問題?我看到的唯一一個是'myArray.lenght = 0;'''長度'拼寫錯誤。 – Dennis 2012-01-16 19:15:29

+0

而不是改變實際路徑的背景爲紅色,只有最差的(最頂部)元素是紅色的,其他綠色 – Tony 2012-01-16 19:18:13

回答

1

點擊事件起源於一個a元素。所以趕在它泡到第一個li之前,並且使所有的a都是默認的。然後繼續my solution

$('#nav a').click(function() { 
    $('#nav a').css('background-color', 'green'); 
}); 
$('#nav li').click(function() { 
    $(this).children('a').css('background-color', 'red'); 
}); 

但它是更好的做這件事的CSS類:

$('#nav a').click(function() { 
    $('#nav a.current').removeClass('current'); 
}); 
$('#nav li').click(function() { 
    $(this).children('a').addClass('current'); 
}); 

而且在CSS:

#nav a { background-color: green; } 
#nav a.current { background-color: red } 
+0

你是主人;)謝謝! – Tony 2012-01-16 19:34:49

+0

你非常歡迎 – ori 2012-01-16 19:40:29

1

你的菜單可能已經嵌套li元素,所以當你點擊一個,事件冒泡,觸發你的回調和清算先前所選的元素。您可以防止事件冒泡,並選擇所有祖先li元素來設置其子女的風格。

$('#nav li').click(function() { 
    //clear the previous selection 
    $('#nav li > a').css("background-color", "green"); 

    //add the new selection 
    $(this).parentsUntil("#nav", "li").children("a").css("background-color", "red"); 

    return false; //Prevent the default action and prevent the event from bubbling up. 
}); 

您可能還想使用類併爲其定義樣式,而不是使用內聯樣式。如果您決定不喜歡這些顏色或想要更多樣式,它將在未來更具可維護性。

+0

它也可以,謝謝:) – Tony 2012-01-16 19:36:32