2012-03-11 44 views
0

下面的代碼在class="hole"的所有元素上執行.css({"background":"black"});,但是我試圖讓它在具有class="hole"data-hole-key="[hole_key_variable]"的元素上執行此操作。jQuery選擇器瘋狂

什麼是缺失?

的jQuery:

// on elements with class "hole" hovered 
$('.hole').hover(
    function(){ 
     // get the data value of the currently hovered element 
     var holeKey = $($(this).data('holeKey')); 
     // on all elements with that class "hole" and specified data value, change bgcolor 
     $('.hole').data(holeKey).css({"background":"black"}); 
    }, 
    function(){ 
     var holeKey = $($(this).data('holeKey')); 
     $('.hole').data(holeKey).removeAttr('style'); 
    } 
); 

HTML:

<td class="hole" data-hole-key="1">text</td> 
<td class="hole" data-hole-key="2">text</td> 
<td class="hole" data-hole-key="3">text</td> 

BTW,爲什麼這(錯誤)的代碼不工作沒有雙重包裝這一行:

var holeKey = $($(this).data('holeKey')); 
+1

您是否嘗試過的組合選擇,例如'$('。hole [data-hole-key]');'? – rjz 2012-03-11 18:39:10

回答

0

這裏有一個工作的jsfiddle什麼,我相信你正在尋找: http://jsfiddle.net/XKs4a/

// on elements with class "hole" hovered 
$('.hole').hover(
    function(){ 
     // get the data value of the currently hovered element 
     var holeKey = $(this).data('holeKey'); 
     // on all elements with that class "hole" and specified data value, change bgcolor 
     $('.hole[data-hole-key=' + holeKey + ']').css({"background":"black"}); 
    }, 
    function(){ 
     var holeKey = $(this).data('holeKey'); 
     $('.hole[data-hole-key=' + holeKey + ']').removeAttr('style'); 
    } 
); 

而對於這一點:

var holeKey = $($(this).data('holeKey')); 

,將返回包裹在jQuery的關鍵,所以對於第一個元素,你會得到$(1)

+0

謝謝,這工作!我不知道方括號的選擇選項。看着它,很多要學習:) – sumsaricum 2012-03-11 19:37:44

0

編輯 反思我認爲你正在嘗試做什麼 - 這第一個文檔片斷將改變懸停元素的CSS只有

$('.hole').hover(
    function(){ 

    $(this).css({"background":"black"}); 
    }, 
    function(){ 

     $(this).removeAttr('style'); 
    } 
); 

在您的代碼導致問題出現,

這裏這部分是不會因爲你是在jQuery的包裝它返回一個值,該值被包裹的是不是一個選擇器

// get the data value of the currently hovered element 
    var holeKey = $($(this).data('holeKey')); 

爲了充分利用要素數據值

// get the data value of the currently hovered element 
    var holeKey = $(this).data('holeKey'); 

要隔離根據其數據值$(「孔」),你可以做這樣的事情:

var testVal=1; 

    $('.hole[data-hole-key="'+ testVal+'"]').hover(..... 

或者其它使用方法過濾器()

var testVal=1; 

    $('.hole').filter(function(){ 
      return $(this).data('data-hole-key')==testVal;     
    }).hover(.... 
+0

謝謝你的回答。第一段代碼並不完全是我所尋找的,但我從下面的部分學到了一些技巧:) – sumsaricum 2012-03-11 19:40:43

+0

描述很難遵循基於非工作代碼作爲參考..答案選擇實際上是一個很長的路要走我編輯的使用「this」的解決方案,並添加額外的DOM搜索到它 – charlietfl 2012-03-11 19:42:02