如何使用 jQuery 禁用标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17552530/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:17:14  来源:igfitidea点击:

How to disable a label with jQuery?

javascriptjqueryhtml

提问by tuco

How can I disable a label with jQuery? I tried:

如何使用 jQuery 禁用标签?我试过:

$('#some-id').prop('disabled', true);

$('#some-id').prop('disabled', true);

but it's not grayed out.

但它没有变灰。

My HTML is: <label for="some-id">Label Here</label><input id="some-id"/>

我的 HTML 是: <label for="some-id">Label Here</label><input id="some-id"/>

回答by Igor

labelsdo not have a disable property inherently built in. You will need to add a class to disable them yourself.

labels没有内置的禁用属性。您需要添加一个类来自己禁用它们。

Something like:

就像是:

.disabled {
   color: darkgrey;
   background-color: grey;
}

And to add the class to your element:

并将类添加到您的元素中:

$('#some-id').addClass('disabled');

回答by Quentin

To disable a label, disable the form control it is associated with.

要禁用标签,请禁用与其关联的表单控件。

That won't change the appearance of the label though, for that you have to change the CSS that applies to it. That is best done by adding (or removing) a class from the element (and having a pre-existing CSS ruleset that matches that class).

但这不会改变标签的外观,因为您必须更改适用于它的 CSS。最好通过从元素中添加(或删除)一个类(并具有与该类匹配的预先存在的 CSS 规则集)来完成。

回答by James Johnson

You can disable an input like this:

您可以禁用这样的输入:

$("#test").attr("disabled", "disabled");

It should be noted that you can't disable a label, as it doesn't accept any input to begin with. If you want it to lookdisabled, you might consider just changing the color of the text to gray.

应该注意的是,您不能禁用标签,因为它一开始不接受任何输入。如果您希望它看起来被禁用,您可以考虑将文本的颜色更改为灰色。

$("#test").css("color", "#666");

回答by ChrisLTD

You should add a disabled class to the label when you disable the input. You could do it like this if you want to keep all the code in the same place:

当您禁用输入时,您应该向标签添加一个禁用类。如果您想将所有代码保留在同一位置,您可以这样做:

$('#some-id, [for="some-id"]').prop('disabled', true).addClass('disabled');

Working JSFiddle example.

工作JSFiddle 示例