jQuery鼠标悬停获取不正确的ID

时间:2011-03-22 23:06:28

标签: javascript jquery css

当鼠标悬停一个div时,我希望实现这一点,div中的相应div就是它们只是悬停显示。比如,当你将鼠标悬停在一个帖子上时,其他选项会自动显示出来?好吧,我做到了.. sorta。我的问题是鼠标悬停GET ID只是最新的一个。

假设我有这个:

<div id="answer-22" class="answer-sep">   

Answer goes here. Lorem impulse dolor...

<div class="answer-footer">
<a title="permalink" class="timestamp-answer" href="#">1 hours, 29 minutes ago</a> by an anonymous poster 
<div class="answer-options" id="options-22" style="float:right;display:none;">

<a id="22" href="#" class="close">[edit]</a> | <a id="22" href="#" class="close">[delete]</a> | <a id="22" href="#" class="report">[report answer]</a>
</div> <!-- end answer-options -->
</div> <!-- end answer footer -->
</div> <!-- end answer-sep -->


<div id="answer-21" class="answer-sep">

Answer goes here. Lorem impulse dolor...

<div class="answer-footer">
<a title="permalink" class="timestamp-answer" href="#">2 hours, 11 minutes ago</a> by an anonymous poster 
<div class="answer-options" id="options-21" style="float:right;display:none;">

<a id="21" href="#" class="close">[edit]</a> | <a id="21" href="#" class="close">[delete]</a> | <a id="21" href="#" class="report">[report answer]</a>
</div> <!-- end answer-options -->
</div> <!-- end answer footer -->
</div> <!-- end answer-sep -->

<div id="answer-20" class="answer-sep">
Answer goes here. Lorem impulse dolor...
<div class="answer-footer">

<a title="permalink" class="timestamp-answer" href="#">4 hours, 49 minutes ago</a> by an anonymous poster 
<div class="answer-options" id="options-20" style="float:right;display:none;">

<a id="20" href="#" class="close">[edit]</a> | <a id="20" href="#" class="close">[delete]</a> | <a id="20" href="#" class="report">[report answer]</a>

</div> <!-- end answer-options -->
</div> <!-- end answer footer -->
</div> <!-- end answer-sep -->

如您所见,它是DIV列表。现在让我说我有这个:

<script type="text/javascript">
$(function() {
    $(".answer-sep").mouseenter(function(){
        var getID = $('.answer-sep').attr("id");
        var theID = getID.split("-");
        alert('Trying to show ID: #'+theID[1]+' and -- ' + getID);
        $('#options-'+theID[1]).slideUp("slow");
        });
    });
</script>

每当我翻转任何一个div时......我得到Trying to show ID: #22 and -- 22这是错误的。它只是最高的一个。帮助

2 个答案:

答案 0 :(得分:4)

这是您用来初始化var getID的选择器。如果jQuery函数实际上只对单个元素有意义(如attr),$('.answer-sep')将对选择器返回的最后一个元素执行该函数。

尝试$(this)代替$('.answer-sep')

答案 1 :(得分:3)

试试这个:

$(function() {
        $(".answer-sep").mouseenter(function(){
            var getID = $(this).attr("id");
            var theID = getID.split("-");
            alert('Trying to show ID: #'+theID[1]+' and -- ' + getID);
            $('#options-'+theID[1]).slideUp("slow");
            });
});