jQuery on hover show for multiple elements

时间:2013-02-09 15:40:03

标签: javascript jquery html css

我有一个包含多行的页面,每行都包含在<div id="result">;

<div id="result"><a href="http://www.domain.com/">Link Name</a><iframe src="http://www.domain.com/" style="width:285px;height:285px;border:0px;margin:0px" scrolling="no"></iframe></div>

我目前正在使用以下jQuery在悬停时显示<a>标记;

$(document).ready(function(){
    $('#result iframe').hover(function(){
        $('#result a').fadeIn(200);
    },function(){
        $('#result a').fadeOut(200);
    });
});

但是,悬停仅适用于第一个<div id="result">,并且还会显示每个<a>的{​​{1}}标记,而不仅仅是用户悬停的标记。

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

假设我理解你的奇怪之处:<​​/ p>

<强> HTML

    <div class="result">
        <a href="http://www.domain.com/" style="display:none;">Link Name</a>
        <iframe src="http://www.domain.com/" style="width:285px;height:285px;border:0px;margin:0px;background:red;" scrolling="no"></iframe>
    </div>
    <div class="result">
        <a href="http://www.domain.com/" style="display:none;">Link Name</a>
        <iframe src="http://www.domain.com/" style="width:285px;height:285px;border:0px;margin:0px;background:red;" scrolling="no"></iframe>
    </div>

<强>的jQuery

$('.result iframe').hover(function(e) {
   $(this).parent().find('a').fadeIn(); 
}, function() {
     $(this).parent().find('a').fadeOut();   
});

请参阅fiddle

使用悬停进行编辑。

如果您不希望通过点击提交链接,请点击事件

Nb:e.preventDefault();

答案 1 :(得分:1)

您可以尝试此操作 - 将results更改为班级

$(document).ready(function(){
    $('.result').hover(function(){ // <-- change to class.. and bind to wrapper div
        $(this).find('a').fadeIn(200);
    },function(){
        $(this).find('a').fadeOut(200);
    });
});

答案 2 :(得分:0)

试试这样:

$(document).ready(function(){
$('#result iframe').hover(function(){
    $('#result a').fadeIn(200);
    $('#result a').fadeOut(200);
});
});

答案 3 :(得分:0)

如果您只想捕获<a>标记,而不是仅针对特定<div id="result">,则可以尝试在jQuery代码中指定,例如:

$(document).ready(function(){
    $('#result:nth-child(1) iframe').hover(function(){
        $('#result:nth-child(1) a').fadeIn(200);
    },function(){
         $('#result:nth-child(1) a').fadeOut(200);
    });
});

因此,这将仅针对id =“result”的第一个div。通过改变n-child(0) - nth-child(1) - nth-child(2)来抓住其他人......

另一个解决方案: 您还可以为每个<a>标记设置ID,或者也可以使用类来捕获所需的特定元素。