开发者

Looping an array together with a jquery hover function

I'm trying to... God, this is hard to explain.

I got an array called 'triggers' with these variables:

"#1_trigger","#2_trigger","#3_trigger"

And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.

What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.

As I said, it's kind of hard to explain what I want to do in text, so here's a demo and开发者_Go百科 my progress so far: http://jsfiddle.net/WJWe3/6/

I've been stuck with this one for too many hours now, please help!


1st, do not name them with a # since you use that in the actual id. (you can add the # in when you need to seek them with jquery)

After that step the code you need is

$("#experiment a").hover(function(){
   $( '#' + this.id.replace('_trigger', '_target') ).show();

}, function(){
   $( '#' + this.id.replace('_trigger', '_target') ).hide();
});

This should be outside of the each loop since it automatically finds the relevant target.

You were also missing a sign = at the point that you assigned the id to the divs.

demo at http://jsfiddle.net/gaby/WJWe3/14/


Something like this maybe?
http://jsfiddle.net/WJWe3/11/


When you set the id for an element, it should not start with #. It's only when you use it as a selector in jQuery that it starts with #.

However, you don't even need to use the id. Create the a and div element as objects instead of as a string, then you can hook up the hover event directly to the link, and access the div directly, instead of trying to find it after adding it to the page.

jsfiddle.net/WJWe3/16/

var triggers = ["1_trigger", "2_trigger", "3_trigger"];

jQuery.each(triggers, function(i, val) {
    var target = $('<div/>', { className: 'hidden' }).text('You found me!');
    var link = $('<a/>', { href: '#' }).text(val).hover(function(){
        target.stop().fadeTo("normal", 1.00);
    }, function(){
        target.stop().fadeTo("normal", 0.00);
    });;
    $("#experiment").append(link).append(target).append("<br/>");
});


here's how i would do this http://jsfiddle.net/WJWe3/15/

<div id="experiment">
    <p><a>test 1</a> <span class='hidden'>hidden 1</span></p>
    <p><a>test 2</a> <span class='hidden'>hidden 2</span></p>
    <p><a>test 3</a> <span class='hidden'>hidden 3</span></p>
</div>

...

$('#experiment a').hover(
    function(){ 
        $(this).siblings('span').stop().fadeTo("normal",1); 
    },
    function(){ 
        $(this).siblings('span').stop().fadeTo("normal",0); 
    }
);


Here's another that works.... Just for fun.

http://jsfiddle.net/WJWe3/18/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜