[英]How to target next() in the same div
I have this HTML
: 我有这个HTML
:
<h3 class="toggle_div">
<i class="left-image switch-icon"></i>
</h3>
I want to change classnames when I click on the div
. 当我单击div
时,我想更改类名。 In this case, left-image should change to a classname right-image . 在这种情况下, left-image应该更改为类名right-image 。
This is the jQuery
I have: 这是我拥有的jQuery
:
$('.toggle-div').click(function(){
$(this).siblings().next('.switch-icon').toggleClass("left-image right-image");
});
I tried this, because the code beneath only works if I put the <i>
element underneath the div element I want to use to toggle. 我尝试了此操作,因为下面的代码仅在将<i>
元素放在要用于切换的div元素下方时才有效。 So it seems like I can't get the classname of the element that is within the div element. 因此,似乎无法获取div元素内的元素的类名。
$('.toggle-div').click(function(){
$(this).next('.switch-icon').toggleClass("left-image right-image");
});
What can I use to make it work? 我可以使用什么来使其正常工作?
JSFiddle : http://jsfiddle.net/f72FY/69/ JSFiddle : http : //jsfiddle.net/f72FY/69/
First of all your class name is wrong in JS. 首先,您的类名称在JS中是错误的。 and then you don't need $(this).siblings().next 然后你不需要$(this).siblings()。next
Just try this 试试这个
$('.toggle_div').click(function(){
$('.switch-icon').toggleClass("left-image right-image");
});
You can use .find()
to find .switch-icon
within the element which is clicked 您可以使用.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 <div class="left-image switch-icon"></div> </h3>
You may use .children Or .find with in the method. 您可以在方法中使用.children或.find。 That should be able to retrieve the full element details based on selector. 那应该能够基于选择器检索完整的元素详细信息。
Try this code 试试这个代码
$('.toggle_div').click(function(){
$('div.switch-icon').toggleClass("left-image right-image");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.