【问题标题】:jQuery selector madnessjQuery 选择器疯狂
【发布时间】:2012-03-11 18:36:54
【问题描述】:

以下代码对所有带有class="hole" 的元素执行.css({"background":"black"});,但是我试图让它在带有class="hole"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:

<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>

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

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

【问题讨论】:

  • 您是否尝试过组合选择器,例如$('.hole[data-hole-key]'); ?

标签: jquery jquery-selectors


【解决方案1】:

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

【讨论】:

  • 谢谢,这行得通!我不知道方括号选择选项。研究一下,有很多东西要学:)
【解决方案2】:

编辑 重新考虑我认为您正在尝试做的事情-第一次剪断只会更改悬停的元素 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(....

【讨论】:

  • 感谢您的回答。第一段代码并不是我要找的,但我从以下部分学到了一些技巧:)
猜你喜欢
  • 2010-09-07
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多