jQuery selector madness

2019-08-23 11:23发布

The following code performs .css({"background":"black"}); on all elements with class="hole", however I'm trying to get it to do it on elements with class="hole" AND data-hole-key="[hole_key_variable]".

What's missing?

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, why does this (faulty) code not work at all without double wrapping this line:

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

2条回答
劳资没心,怎么记你
2楼-- · 2019-08-23 11:37

EDIT Rethinking what I think you are trying to do- this first snipped will change the hovered element CSS only

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

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

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

WHere your code is causing issues

This part here is not going to return a value because you are wrapping it in jQuery, and the value being wrapped is not a selector

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

To get the value from element data

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

To isolate a $('.hole') based on its data value you could do something like this:

 var testVal=1;

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

Or another method using filter()

    var testVal=1;

    $('.hole').filter(function(){
            return $(this).data('data-hole-key')==testVal;                 
    }).hover(....
查看更多
▲ chillily
3楼-- · 2019-08-23 11:52

Here's a working jsfiddle of what I believe you're looking for: 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');
    }
);

And for this:

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

That would return the key wrapped in jquery, so for the first element you would get $(1)

查看更多
登录 后发表回答