twitter-bootstrap 更改切换按钮内的图标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19142762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing an icon inside a toggle button?
提问by zazvorniki
I have a button that has an icon in it, and I have some jQuery code opening and closing a div.
我有一个按钮,里面有一个图标,我有一些 jQuery 代码打开和关闭一个 div。
I have some code that switches the icon from a plus to minus, but the issue is that I have to click directly on the icon for it to work instead being able to click anywhere on the button, and that can be an issue for the minus icon.
我有一些代码可以将图标从加号切换为减号,但问题是我必须直接单击图标才能工作,而不是能够单击按钮上的任何位置,这可能是减号的问题图标。
My HTML looks like this:
我的 HTML 如下所示:
<button class="pull-right toggleBtn span1"><i class="icon-plus"></i></button>
and my jQuery to switch the icons looks like this:
和我的 jQuery 切换图标看起来像这样:
$(".toggleBtn").on('click','.icon-minus, .icon-plus',function(){
$(this).toggleClass("icon-minus icon-plus");
});
Any help would be awesome!
任何帮助都是极好的!
回答by Joshua Dwire
Change your JavaScript code to this:
将您的 JavaScript 代码更改为:
$(".toggleBtn").on('click',function(){
$(this).children('.icon-minus, .icon-plus').toggleClass("icon-minus icon-plus");
});
Your current code only listens to the click event on the icon. This code will listen to the click event on the entire button but still change the class only on the icon.
您当前的代码仅侦听图标上的点击事件。此代码将侦听整个按钮上的单击事件,但仍仅更改图标上的类。
JSFiddle: http://jsfiddle.net/jdwire/B4avV/
JSFiddle:http: //jsfiddle.net/jdwire/B4avV/
回答by Bala
try this
试试这个
$(document).on('click','.toggleBtn',function(){
$(this).children().toggleClass("icon-minus icon-plus");
});
回答by Unknown
Try:
尝试:
$(document).on('click','.toggleBtn',function(){
if ($(this).children().is('.icon-plus')) {
$(this).children().removeClass('icon-plus');
}else{
$(this).children().addClass('icon-plus');
}
});

