在 jQuery 中添加属性

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

Adding attribute in jQuery

jqueryhtmltags

提问by Yuda Prawira

How can I add an attribute into specific HTML tags in jQuery?

如何将属性添加到 jQuery 中的特定 HTML 标签中?

For example, like this simple HTML:

例如,像这个简单的 HTML:

<input id="someid" />

Then adding an attribute disabled="true" like this:

然后添加一个属性 disabled="true" 像这样:

<input id="someid" disabled="true" />

回答by Paul Rosania

You can add attributes using attrlike so:

您可以attr像这样添加属性:

$('#someid').attr('name', 'value');

However, for DOM properties like checked, disabledand readonly, the proper way to do this (as of JQuery 1.6) is to use prop.

但是,对于checkeddisabled和等 DOM 属性,readonly执行此操作的正确方法(从 JQuery 1.6 开始)是使用prop.

$('#someid').prop('disabled', true);

回答by diEcho

best solution:from jQuery v1.6 you can use prop()to add a property

最佳解决方案:从 jQuery v1.6 开始,您可以使用 prop()添加属性

$('#someid').prop('disabled', true);

to remove it, use removeProp()

要删除它,请使用 removeProp()

$('#someid').removeProp('disabled');

Reference

Reference

Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.

另请注意,不应使用 .removeProp() 方法将这些属性设置为 false。一旦删除了本机属性,就无法再次添加它。有关更多信息,请参阅 .removeProp()。

回答by mattsven

You can do this with jQuery's .attrfunction, which will set attributes. Removing them is done via the .removeAttrfunction.

您可以使用 jQuery 的.attr函数来设置属性。删除它们是通过.removeAttr函数完成的。

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");

回答by Jerad Rose

$('#someid').attr('disabled', 'true');

回答by mrzmyr

$('#someid').attr('disabled', 'true');

回答by morgar

$('.some_selector').attr('disabled', true);

回答by amar ghodke

Add attribute as:

添加属性为:

$('#Selector_id').attr('disabled',true);

回答by Vildan Bina

use this code <script> $('#someid').attr('disabled,'true'); </script>

使用此代码 <script> $('#someid').attr('disabled,'true'); </script>

回答by Rejwanul Reja

This could be more helpfull....

这可能更有帮助......

$("element").prop("id", "modifiedId");
//for boolean
$("element").prop("disabled", true);
//also you can remove attribute
$('#someid').removeProp('disabled');

回答by Nakendra Pun

$('#yourid').prop('disabled', true);