有时我使用样式为按钮的锚,有时我只使用按钮。我想禁用特定的点击东西,以便:
他们看起来很残疾 它们不再被点击
我该怎么做呢?
有时我使用样式为按钮的锚,有时我只使用按钮。我想禁用特定的点击东西,以便:
他们看起来很残疾 它们不再被点击
我该怎么做呢?
当前回答
假设你有这样的,目前是启用的。
<button id="btnSave" class="btn btn-info">Save</button>
只要加上这个:
$("#btnSave").prop('disabled', true);
你会得到这个,它会禁用按钮
<button id="btnSave" class="btn btn-primary" disabled>Save</button>
其他回答
注意,如果你使用Bootstrap的JS按钮和“loading”状态,会有一个奇怪的问题。我不知道为什么会发生这种情况,但这里有如何解决它。
假设你有一个按钮,并将其设置为加载状态:
var myButton = $('#myBootstrapButton');
myButton.button('loading');
现在你想把它从加载状态中拿出来,但也要禁用它(例如,按钮是一个保存按钮,加载状态表明正在进行验证,验证失败)。这看起来像合理的Bootstrap JS:
myButton.button('reset').prop('disabled', true); // DOES NOT WORK
不幸的是,这将重置按钮,但不会禁用它。显然,button()执行一些延迟的任务。所以你也必须推迟你的残疾:
myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);
有点烦人,但这是我经常使用的模式。
如果你想禁用可点击,你也可以在html中添加内联这个
style="cursor: not-allowed;"
所有人的回答和贡献都很棒!我不得不稍微扩展这个功能,包括禁用选择元素:
jQuery.fn.extend({
disable: function (state) {
return this.each(function () {
var $this = jQuery(this);
if ($this.is('input, button'))
this.disabled = state;
else if ($this.is('select') && state)
$this.attr('disabled', 'disabled');
else if ($this.is('select') && !state)
$this.removeAttr('disabled');
else
$this.toggleClass('disabled', state);
});
}});
似乎对我有用。感谢所有!
下面这些方法对我来说非常有效:
$("#button").attr('disabled', 'disabled');
对于这种行为,我总是使用jQueryUI按钮小部件,我将它用于链接和按钮。
在HTML中定义标签:
<button id="sampleButton">Sample Button</button>
<a id="linkButton" href="yourHttpReferenceHere">Link Button</a>
使用jQuery初始化按钮:
$("#sampleButton").button();
$("#linkButton").button();
使用按钮小部件方法禁用/启用它们:
$("#sampleButton").button("enable"); //enable the button
$("#linkButton").button("disable"); //disable the button
这将处理按钮和游标行为,但如果您需要深入了解并在禁用时更改按钮样式,那么请在页面CSS样式文件中覆盖以下CSS类。
.ui-state-disabled,
.ui-widget-content .ui-state-disabled,
.ui-widget-header .ui-state-disabled {
background-color:aqua;
color:black;
}
但是请记住:这些CSS类(如果改变了)也会改变其他小部件的样式。