jQuery 如何设置jquery按钮活动状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6665348/
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
how to set jquery button active state
提问by Sherry
I have this right navigation that uses the jquery button. If the user clicks it, the page will load. What I need is once the page reload, the button should show that it was selected.
我有这个使用 jquery 按钮的正确导航。如果用户点击它,页面将加载。我需要的是页面重新加载后,按钮应显示它已被选中。
How do I do this using the jquery button?
如何使用 jquery 按钮执行此操作?
回答by jyore
Why don't you use the jQuery UI Tab widget? You could also try using the buttonset widget?
为什么不使用 jQuery UI Tab 小部件?您也可以尝试使用按钮组小部件?
If those are not optimal for you, then you can use some CSS stuff to your advantage. The following code sets up two jQuery UI buttons that will keep their active state when clicked, remove the active state from the other, and update a div with which has been clicked.
如果这些对你来说不是最佳的,那么你可以使用一些 CSS 的东西来发挥你的优势。以下代码设置了两个 jQuery UI 按钮,它们将在被点击时保持活动状态,从另一个中删除活动状态,并更新已被点击的 div。
HTML
HTML
<button id="btn" class='nav'>Button 1</button>
<button id="btn2" class='nav'>Button 2</button>
<div id="data">Init....</div>
JavaScript
JavaScript
$(function() {
//Variable of previously selected
var selected = [];
//Setup Buttons
$('.nav').button().click(function() {
//Enable previous
if(selected[0]) {
selected.button('enable').removeClass('ui-state-active ui-state-hover');
}
//Cache the previous
selected = $(this);
//Disable this and keep color attributes
selected.button('disable').addClass('ui-state-active').removeClass('ui-state-disabled');
//Do Normal Button Click Stuff Here
$('#data').text(selected.text() + ' was clicked');
});
$('#btn').click();
});
回答by G.A.
$('#mybutton').button().bind('click', function(){
$(this).addClass('ui-state-focus');
});
This keeps it in focussed state (ie., highlighted as per jquery ui theme you have selected). Of course, you need to remove this class from all the other buttons on your toolbar.
这使其保持在聚焦状态(即,根据您选择的 jquery ui 主题突出显示)。当然,您需要从工具栏上的所有其他按钮中删除此类。
回答by Kokos
If your button goes to a new page, you will need to use either your server side language or html (depending on your setup) to switch the classes.
如果您的按钮转到新页面,您将需要使用服务器端语言或 html(取决于您的设置)来切换类。
If your button refreshes the current page with new content, you can use something like the following:
如果您的按钮使用新内容刷新当前页面,您可以使用以下内容:
.active { font-weight:bold; }
$('#button').addClass('active');
回答by ShankarSangoli
Once the page load add a css class to button. Have some styles for this class which will indicate that it is selected.
页面加载后,向按钮添加一个 css 类。为此类提供一些样式,这将表明它已被选中。