0

正如标题所说,我尝试将 jquery 悬停效果添加到 for 循环中的不同 a-tags。添加了悬停效果,但里面的隐藏显示功能似乎是错误的。我总是得到最后一个 li 元素的选择器。

任何帮助都会很棒。

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

这是代码:

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>
    <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();
    });
}
4

3 回答 3

1

您可以将其简化为:

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

于 2011-06-27T13:29:26.303 回答
1

请查看这个小提琴: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>

情侣笔记:

  1. jQuery 内置了循环。如果您应用类似 的操作.hide(),它会将其应用于整个集合。如果您编写一个for循环来遍历 jQuery 集合,那么您做错了。
  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.
于 2011-06-27T13:31:33.143 回答
0

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/

于 2011-06-27T13:39:15.330 回答