gpt4 book ai didi

jquery - 禁用/启用按钮和链接的最简单方法是什么(jQuery + Bootstrap)

转载 作者:bug小助手 更新时间:2023-10-28 10:55:04 29 4
gpt4 key购买 nike

有时我使用样式为按钮的 anchor ,有时我只使用按钮。我想禁用特定的 clicky-things 以便:

  • 他们看起来很残疾
  • 它们不再被点击

我该怎么做?

最佳答案

按钮

按钮很容易禁用,因为 disabled 是一个由浏览器处理的按钮属性:

<input type="submit" class="btn" value="My Input Submit" disabled/>
<input type="button" class="btn" value="My Input Button" disabled/>
<button class="btn" disabled>My Button</button>

要使用自定义 jQuery 函数禁用这些,您只需使用 fn.extend() :

// Disable function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});

// Disabled with:
$('input[type="submit"], input[type="button"], button').disable(true);

// Enabled with:
$('input[type="submit"], input[type="button"], button').disable(false);

JSFiddle disabled button and input demo .

否则你会使用 jQuery 的 prop()方法:

$('button').prop('disabled', true);
$('button').prop('disabled', false);

anchor 标记

值得注意的是 disabled 不是 valid property用于 anchor 标签。因此,Bootstrap 在其 .btn 元素上使用以下样式:

.btn.disabled, .btn[disabled] {
cursor: default;
background-image: none;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
color: #333;
background-color: #E6E6E6;
}

注意 [disabled] 属性以及 .disabled 类是如何定位的。 .disabled 类是使 anchor 标记显示为禁用所需要的。

<a href="http://example.com" class="btn">My Link</a>

当然,这不会阻止链接在单击时起作用。以上链接将带我们到http://example.com .为了防止这种情况,我们可以添加一段简单的 jQuery 代码来定位带有 disabled 类的 anchor 标记来调用 event.preventDefault() :

$('body').on('click', 'a.disabled', function(event) {
event.preventDefault();
});

我们可以使用 toggleClass() 切换 disabled 类:

jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
var $this = $(this);
$this.toggleClass('disabled', state);
});
}
});

// Disabled with:
$('a').disable(true);

// Enabled with:
$('a').disable(false);

JSFiddle disabled link demo .


结合

然后我们可以扩展前面的禁用函数来检查我们尝试使用 is() 禁用的元素的类型.这样我们可以 toggleClass() 如果它不是 inputbutton 元素,或者切换 disabled如果是属性:

// Extended disable function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
var $this = $(this);
if($this.is('input, button, textarea, select'))
this.disabled = state;
else
$this.toggleClass('disabled', state);
});
}
});

// Disabled on all:
$('input, button, a').disable(true);

// Enabled on all:
$('input, button, a').disable(false);

Full combined JSFiddle demo .

值得注意的是,上述函数也适用于所有输入类型。

关于jquery - 禁用/启用按钮和链接的最简单方法是什么(jQuery + Bootstrap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16777003/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com