2012-03-11 51 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