开发者

Adding jQuery hover effect within a for loop doesn't work

As the title says, i try to add a jquery hover effect to different a-tags within a for loop. The hover-effects are added but the hide-show-functionality inside seems to be wrong. i always get the selector for the last li-element.

Any help would be great.

http://jsfiddle.net/pGgeW/1/

here's the code:

html:

<a id="o1" href="#">Show Text 1</a>
<a id="o2" href="#">Show Text 2</a>
<a id="o3" href="#">Show Text 3</a>
<a id="o4" href="#">Show Text 4</a>
<a id="o5" href="#">Show Text 5</a>

<ul class="subTxt">
    <li id="u1">Text 1</li>
    <li id="u2">Text 2</li>
    <li id="u3">Text 3</li>
    <li id="u4">Text 4</li>开发者_StackOverflow社区
    <li id="u5">Text 5</li>
</ul>

javascript:

/* Hide li's */
$("ul.subTxt").find("li").each(

function() {
    $(this).hide();
});

/* Add Hover-Events */
for (var a = 1; a < 6; a++) {
    var k = '#o' + a;
    var e = '#u' + a;
    $(k).hover(

    function() {
        $(e).show();
        $(this).append('<div id="hk" style="position: relative;float: right;">' + k + ' ' + e + '</div>');
    }, function() {
        $(e).hide();
        $(this).find('#hk').remove();
    });
}


You can simplify it to this:

/* Hide li's */
$("ul.subTxt li").hide();

$("a.hover").hover(function(){
    var n = this.id.replace("o","");
    $("#u"+n).show();
}, function() {
    var n = this.id.replace("o","");
    $("#u"+n).hide();
});

http://jsfiddle.net/petersendidit/pGgeW/3/


Please review this fiddle: http://jsfiddle.net/pGgeW/9/

$("ul.subTxt").find("li").hide();

$("a").hover(function(e) {
    $($(this).attr('href')).toggle();
}).click(function() { return false; });

HTML:

<a href="#u1">Show Text 1</a>
<a href="#u2">Show Text 2</a>
<a href="#u3">Show Text 3</a>
<a href="#u4">Show Text 4</a>
<a href="#u5">Show Text 5</a>

<ul class="subTxt">
    <li id="u1">Text 1</li>
    <li id="u2">Text 2</li>
    <li id="u3">Text 3</li>
    <li id="u4">Text 4</li>
    <li id="u5">Text 5</li>
</ul>

Couple notes:

  1. jQuery has looping built in. If you apply an operation like .hide(), it applies it to the entire collection. If you write a for loop to iterate over a jQuery collection, you're doing it wrong.
  2. Generally you'll want to use a technique which associates your anchor tag with the target it's acting upon. Commonly this is done with the href attribute when the href isn't an external page and instead an internal reference (which uses the # sign). You'll see that I used it as a reference to the associated LI ID.


The problem is that the e and k variables are global. One option would be to wrap that code in a function. This way e and k are local to that function. Like so:

http://jsfiddle.net/pGgeW/8/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜