jQuery选择器疯狂 [英] jQuery selector madness

查看:140
本文介绍了jQuery选择器疯狂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]".

缺少什么?

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'));

推荐答案

以下是我认为您正在寻找的有效的jsfiddle: http://jsfiddle.net/XKs4a/

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');
    }
);

为此:

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

这将返回包装在jquery中的键,因此对于第一个元素,您将获得$(1)

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

这篇关于jQuery选择器疯狂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆