开发者

jQuery selective hover

I'm trying to do a simple task with jQuery: I have a list of words which, when hovered, sho开发者_如何学Culd fadeIn its corresponding image. For example:

<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>

<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">

I'm currently doing it this way for each link/image:

$('a.yellow').hover(
  function () {
    $('img.yellow').fadeIn('fast');
    },
    function () {
     $('img.yellow').fadeOut('fast');
     });

The method above works fine, but as I'm still learning, I guess there's a better way to do that instead of repeating functions.

Can anyone give me some light here? How can I improve this code?


<a href="#" class="yellow" data-type="color">Yellow</a>
<a href="#" class="blue" data-type="color">Blue</a>
<a href="#" class="green" data-type="color">Green</a>

jQuery Code

$('a[data-type=color]').hover(
  function () {
    $('img.'+$(this).attr("class")).fadeIn('fast');
    },
    function () {
     $('img.'+$(this).attr("class")).fadeOut('fast');
     });
});

I think you should try this one. I used data- as prefix for custom defined attributes because it is html5 compliant. You can say data-something if you want to.

Normally you may not need to use data-color custom attribute but since I think to make it more generic, I used that attribute. You can do such code as well :

<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>

Then

$('a').hover(
  function () {
    $('img.'+$(this).attr("class")).fadeIn('fast');
    },
    function () {
     $('img.'+$(this).attr("class")).fadeOut('fast');
     });
});

But this way, you should make sure all the links are image related links.


<a href="#" id="yellow" class="colorLink">Yellow</a>
<a href="#" id="blue" class="colorLink">Blue</a>
<a href="#" id="green" class="colorLink">Green</a>

<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">

$("a.colorLink").hover(
    function(){
        $("img."+this.id).fadeIn('fast');
    },
    function(){
        $("img."+this.id).fadeOut('fast');
    }
);

This sets a unique id to each link that corresponds to the image.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜