jQuery选择器疯狂

以下代码执行.css({"background":"black"}); 在所有带有class="hole"元素上,但是我试图让它在class="hole" AND data-hole-key="[hole_key_variable]"

少了什么东西?

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:

 text text text 

顺便说一句,为什么这个(错误的)代码在没有双重包装这条线的情况下根本不起作用:

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

这是我认为你正在寻找的工作方式: 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)

编辑重新思考我认为你想要做的事情 – 这首先剪切将只改变hover元素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'); 

要根据数据值隔离$(’。hole’),您可以执行以下操作:

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

或者使用filter()的另一种方法

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