有时我使用样式为按钮的锚,有时我只使用按钮。我想禁用特定的点击东西,以便:

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

我该怎么做呢?


当前回答

假设你有文本框和提交按钮,

<input type="text" id="text-field" />
<input type="submit" class="btn" value="Submit"/>

禁用:

要禁用任何按钮,例如,提交按钮,你只需要添加disabled属性为,

$('input[type="submit"]').attr('disabled','disabled');

执行上述代码行后,你的提交按钮html标签看起来是这样的:

<input type="submit" class="btn" value="Submit" disabled/>

注意添加了'disabled'属性。

启用:

用于启用按钮,例如当文本字段中有一些文本时。您将需要删除启用按钮的禁用属性,

 if ($('#text-field').val() != '') {
     $('input[type="submit"]').removeAttr('disabled');
 }

现在上面的代码将删除'disabled'属性。

其他回答

所有人的回答和贡献都很棒!我不得不稍微扩展这个功能,包括禁用选择元素:

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);
    });
}});

似乎对我有用。感谢所有!

我想不出更简单的办法了!: -)


使用锚标签(链接):

<a href="#delete-modal" class="btn btn-danger" id="delete">Delete</a>

要启用Anchor标签:

 $('#delete').removeClass('disabled');
 $('#delete').attr("data-toggle", "modal");


禁用Anchor标签:

 $('#delete').addClass('disabled');
 $('#delete').removeAttr('data-toggle');

假设你在页面上有这样的按钮:

<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit"value="Enable All" onclick="change()"/>

js代码:

function change(){
   var toenable = document.querySelectorAll(".byBtn");        
    for (var k in toenable){
         toenable[k].removeAttribute("disabled");
    }
}

上面的方法并不管用,因为有时候

$(this).attr('checked') == undefined

使用以下命令调整代码

if(!$(this).attr('checked') || $(this).attr('checked') == false){

假设你有这样的,目前是启用的。

<button id="btnSave" class="btn btn-info">Save</button>

只要加上这个:

$("#btnSave").prop('disabled', true);

你会得到这个,它会禁用按钮

<button id="btnSave" class="btn btn-primary" disabled>Save</button>