【问题标题】:How to use the tilde selector with (this) jquery如何在(this)jquery中使用波浪号选择器
【发布时间】:2015-06-23 17:01:41
【问题描述】:

大家下午好,我正在尝试在 div 中选择一个特定的同级。我尝试过使用我发现的许多不同的建议,但似乎都无法奏效。使用this,看起来我可以使用这样的东西:

$( "#prev ~ div" ).css( "border", "3px groove blue" );

但是,我想在选择器中使用 (this),可能是这样:

&(this " ~ p").show();

基本上,我只是想在触发某个事件时显示一个段落兄弟。如果有人有更好的方法,我很乐意接受建议。我尝试过其他方法,例如使用 next() 和兄弟姐妹("p") 但似乎无法让它工作。这是我目前拥有的html和jquery的一部分。

<div class="col-sm-8 items">
    <div class="item">
        <h6>Dynamic Web Programming<h6>
        <img src="DynamicWebProgramming.jpg">
        <p>This book is a great tool for learning to develop Dynamic Web Pages.</p>  
         // This is the paragraph that is hidden and I want to show on mouseover
    </div>
</div>

$(document).ready(function() {
    $(".item p").hide();

    $(".item h6").mouseover(function() {
        $(this).addClass("mouseover");
        $(this).siblings().addClass("mouseover");
        $(this).siblings("p").show(); // This is where I want to call .show() for the 
                                         specific sibling
    })

    $(".item p").click(function() {
        $(this).removeClass("mouseover");
        $(this).siblings().removeClass("mouseover");
    })
})

如果有人能提供任何建议,那就太好了! 谢谢, 安迪

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    你在正确的轨道上,我将鼠标悬停改为悬停:

    $(".item h6").hover(function() {
        $(this).toggleClass("mouseover");
        $(this).siblings().toggleClass("mouseover");
        $(this).siblings("p").show(); // This is where I want to call .show() for the  specific sibling
    },function(){
        $(this).toggleClass("mouseover");
        $(this).siblings().toggleClass("mouseover");
        $(this).siblings("p").hide();
    });
    

    fiddle这里

    【讨论】:

    • 很有趣,非常感谢!你介意我问为什么 $(this).siblings("p").show() 不适用于鼠标悬停吗?我问的原因是因为我不想让段落在不再悬停时再次隐藏。我可以通过从 handlerOut 函数中删除 .hide() 来实现这一点,但我不明白为什么它在鼠标悬停时不起作用。再次感谢!
    • 它似乎对我有用,但我以为你想切换它。它正在使用您的代码:jsfiddle.net/depperm/0qc1muw4
    • @AndyGiebel hover 使用 mouseenter 而不是 mouseoverapi.jquery.com/mouseenter
    • 是的,更奇怪的是,我能够让它与小提琴一起使用,但是当我将它移到我的 js 文件时,它仍然无法正常工作!另外,我确实希望它切换,但只能在单击时切换。 (我知道这看起来很奇怪,但这是出于学习目的:D)
    • 嗯,非常感谢您的帮助,但是您知道为什么我可以让它在 jsfiddle 上运行,但不能在本地运行吗?我正在使用 jquery 1.11.3(jsfiddle 与 1.11.0 一起使用)。我知道悬停和鼠标悬停工作正常,因为它应该添加鼠标悬停类。由于某种原因,它仍然只是不喜欢 $(this).siblings("p").show();再次感谢
    猜你喜欢
    • 2013-02-03
    • 2022-12-28
    • 2011-01-28
    • 2010-09-19
    • 1970-01-01
    • 2012-08-18
    • 2012-06-02
    • 2020-03-13
    相关资源
    最近更新 更多