[英]how to swap an image in javascript
Im trying to do a show/hide function, but I having a problem in swapping the image(bootstrap class). 我正在尝试执行显示/隐藏功能,但是在交换图像(bootstrap类)时遇到问题。 The show-hide function is working, the problem is that I don't know how to detect which class is in display....with the code that I have I am able to change the class from min to plus....then the user click again the button, it display the content but it remains the plus class.
show-hide函数正在运行,问题是我不知道如何检测正在显示的类。用我拥有的代码,我可以将类从min更改为plus。然后用户再次单击该按钮,它将显示内容,但仍为plus类。
HTMl. HTM1。
<span class="glyphicon show-hide glyphicon-minus"></span>
JS. JS。
$('.glyphicon-minus').click(function()
{
$('.show-hide').removeClass('glyphicon-minus').addClass('glyphicon-plus');
$(this).closest('div').next('.widget-content').slideToggle();
var $classto = $('.glyphicon-plus');
$classto.is(':visible')
{
$('.show-hide').removeClass('glyphicon-plus').addClass('glyphicon-minus');
}
})
$('.show-hide').on('click', function(){
var $this = $(this);
if($this.hasClass('glyphicon-minus')) {
$this
.removeClass('glyphicon-minus')
.addClass('glyphicon-plus')
.closest('div')
.next('.widget-content')
.slideUp();
}
else {
$this
.removeClass('glyphicon-plus')
.addClass('glyphicon-minus')
.closest('div')
.next('.widget-content')
.slideDown();
}
});
Or, assuming your html is correctly initialized: 或者,假设您的html已正确初始化:
$('.show-hide').on('click', function(){
$(this)
.toggleClass('glyphicon-plus glyphicon-minus')
.closest('div')
.next('.widget-content')
.slideToggle();
});
(Generally, you don't want to mix toggle functions with non-toggle functions.) (通常,您不希望将切换功能与非切换功能混合使用。)
The reason the glyphicon-plus class remained mainly is because you targetted ".glyphicon-minus" class in your event listener. 保留glyphicon-plus类的原因主要是因为您在事件侦听器中定位了“ .glyphicon-minus”类。 But when you change your class glyphicon-minus does not exist.
但是,当您更改类时,glyphicon-minus不存在。 Switching that you to a class that remains on the element should do the trick.
将您切换到保留在元素上的类应该可以解决问题。
I also refactored your code a bit. 我也重构了您的代码。
$('.show-hide').on("click",function()
{
if ($(this).hasClass("glyphicon-minus")){
$(this).removeClass('glyphicon-minus').addClass('glyphicon-plus');
}else{
$(this).removeClass('glyphicon-plus').addClass('glyphicon-minus');
}
$(this).closest('div').next('.widget-content').slideToggle();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.