2017-11-11 44 views
0

目标我有这个HTML怎样的next()在同一div

<h3 class="toggle_div"> 
     <i class="left-image switch-icon"></i> 
    </h3> 

我想改变的类名,当我点击div。在这种情况下,左图应更改为类名右图

这是jQuery我:

$('.toggle-div').click(function(){ 
    $(this).siblings().next('.switch-icon').toggleClass("left-image right-image"); 
}); 

我想这一点,因为下面的代码只有当我把<i>元素的div元素我想用来切换工作底下。因此,我似乎无法获取div元素内的元素的类名。

$('.toggle-div').click(function(){ 
    $(this).next('.switch-icon').toggleClass("left-image right-image"); 
}); 

我可以用什么来使它工作?

的jsfiddlehttp://jsfiddle.net/f72FY/69/所有的类名

+2

类的名字是错的JavaScript。它的toggle_div不是toggle-div –

+1

'.switch-icon'不是'toggle_div'的兄弟 - 它是一个子元素。 '$(this).find(“。switch-icon”)' –

+1

http://jsfiddle.net/f72FY/70/ –

回答

1

您可以使用.find()到被点击的元素中找到.switch-icon

$('.toggle_div').click(function(){ 
 
     $(this).find('.switch-icon').toggleClass("left-image right-image"); 
 
    });
.left-image 
 
{ 
 
background-image: url('http://i.stack.imgur.com/euD9p.png'); 
 
    width:20px; 
 
    height:20px; 
 
    background-repeat: no-repeat; 
 
    
 
} 
 
.right-image 
 
{ 
 
background-image: url('http://i.stack.imgur.com/dzs9m.png'); 
 
    width:20px; 
 
    height:20px; 
 
    background-repeat: no-repeat; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
     <h3 class="toggle_div"> 
 
     Clicking on this text should toggle 
 
     \t \t <div class="left-image switch-icon"></div> 
 
     </h3>

1

首先是错误的JS。然后你不需要$(本).siblings()。接下来

刚刚尝试这一点

$('.toggle_div').click(function(){ 
    $('.switch-icon').toggleClass("left-image right-image"); 
}); 
+0

谢谢!现在明白了。 – Siyah

+0

在20分钟的时间内,OP提出了一个新问题:我单击一个div,它会更改所有的开关图标,我如何才能使其更改为一个... –

1

您可以在方法中使用.children或.find with。这应该能够根据选择器检索完整的元素细节。

0

试试这个代码

$('.toggle_div').click(function(){ 
        $('div.switch-icon').toggleClass("left-image right-image"); 
    });