【问题标题】:How to change background-image for only next h2如何仅更改下一个 h2 的背景图像
【发布时间】:2015-02-17 02:30:00
【问题描述】:

jquery

 $(document).ready(function() {
    $(".nag").click(function(){
        $(".nag").not(this).next(".zaw").slideUp("slow");
        $(this).next(".zaw").slideToggle("slow");
        $("h2").css("background-image", "url(img/arr_top.png)");    
        });
    });

HTML

    <div class="nag">
       <h2>H2</h2>
    </div>
    <div class="zaw">
     </div>
<div class="nag">
       <h2>H2</h2>
    </div>
    <div class="zaw">
     </div> 
<div class="nag">
       <h2>H2</h2>
    </div>
    <div class="zaw">
     </div>     

嗨,这是我在单击其中一个 div 后向上滑动 div 的代码。第二次单击slideToggle 后。

我应该在 jquery 中添加什么来仅在单击后更改下一个 h2 的背景图像(现在单击后所有 h2 都更改了),并且在第二次单击后背景图像返回到背景图像的第一个值 (img/arr.png )

非常感谢您的帮助,因为这件事看起来很简单,我有两天在不同的地方添加.next() :)

【问题讨论】:

  • 你的下一个H2在哪里?我想你正在寻找$(this).find("h2")

标签: jquery css background-image next


【解决方案1】:

h2 位于 div 下,所以它应该是,否则它将在全球范围内生效

$(this).children("h2")

$(document).ready(function() {
  $(".nag").click(function() {
    $(".nag").not(this).next(".zaw").slideUp("slow");
    $(this).next(".zaw").slideToggle("slow");
    $(this).children("h2").toggleClass('bg')
  });
});
.nag {
  border: 1px solid red;
}
.bg {
  background-image: url(http://placeimg.com/640/480/any);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="nag">
  <h2>H2</h2>
</div>
<div class="zaw"></div>

【讨论】:

  • 我的 2 天 = 你的 5 分钟 - 谢谢!第二次点击后回到第一个值怎么样?这很难吗?
  • 而是添加一个带有背景图像的类并像我在 sn-p @Michal 中所做的那样切换它
【解决方案2】:

目前您正在获取全局选择器,即 h2,而不是在单击的元素内使用 h2。

替换这个:

$("h2").css("background-image", "url(img/arr_top.png)");   

有了这个:

$(this).find("h2").css("background-image", "url(img/arr_top.png)");   

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多