如果父div具有Class(),则显示span

Ste*_*gie 2 html javascript css jquery

我正用这个打败自己.我不知道在做什么.这很简单,但它不起作用.我希望spandiv有a 时显示一个项目class.是的,基本的,但我不能让它工作.

这是我的HTML与类 add-product

<div id="ot-pr" class="status-publish has-post-thumbnail hentry add-product">
    <span class="arrow">Testing</span>
</div>
Run Code Online (Sandbox Code Playgroud)

这是JavaScript

$(document).ready(function($){
    if ($("#ot-pr").hasClass('add-product')){
        $(".arrow").show();
    } else { 
        $(".arrow").hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

这是CSS的CSS .arrow

.arrow {
    display: none;
    width: 0; height: 0;
    line-height: 0;
    border-right: 16px solid transparent;
    border-top: 10px solid #c8c8c8;
    top: 60px;
    right: 0;
    position: absolute;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了什么,添加find(span)并添加else if:

$(document).ready(function(){
    if ($("#ot-pr").hasClass('add-product')){
        $(".arrow").find('span').show();
    } else if { 
        $(".arrow").hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

单独或一起不起作用.为什么这不起作用.这应该是基本的吗?!我没有收到控制台错误,并jQuery.js已添加到页面中.所有其他脚本工作得很好.

Ror*_*san 9

这里不需要JS,你可以在CSS中实现这一点:

.arrow {
  display: none;    
  /* simplified CSS for the example */
}
div.add-product .arrow {
  display: block;
}
Run Code Online (Sandbox Code Playgroud)
<div id="ot-pr" class="status-publish has-post-thumbnail hentry add-product">
  <span class="arrow">arrow 1</span>
</div>

<div id="ot-pr" class="status-publish has-post-thumbnail hentry add-product">
  <span class="arrow">arrow 2</span>
</div>

<!-- not visible -->
<div id="ot-pr" class="status-publish has-post-thumbnail hentry">
  <span class="arrow">arrow 3</span>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 只有 CSS 吗?不知道这是什么魔法……:D (2认同)