简体   繁体   English

如何使用jQuery在DOM元素中添加非值属性

[英]How to add a non-value attribute in a DOM element with jQuery

I want to add a property on DOM elements using jQuery. 我想使用jQuery在DOM元素上添加一个属性。

The attribute is disabled, which bootstrap uses this attribute to disable an element. 该属性被禁用,引导程序使用此属性禁用元素。 eg 例如

<p>A paragraph</p>

and want it to become 并希望它成为

<p disabled> A paragraph </p>

But running the following code 但是运行以下代码

$('p').attr('disabled', '');

gives me: 给我:

<p disabled="disabled"><A paragraph</p>

Tried using prop() but prop didn't even add the property. 使用prop()尝试过,但是prop甚至没有添加该属性。

$('p').prop('disabled','');

How can I add a non-value attribute using jQuery? 如何使用jQuery添加非值属性?

Or what am I doing wrong? 还是我做错了什么?

You are dealing with a DOM, not with HTML. 您正在处理DOM,而不是HTML。 disabled and disabled="disabled" are equivalent and there is no way to tell the browser how (when serialising to HTML) it should serialise an attribute which can be serialised in multiple ways. disableddisabled="disabled"是等效的,并且无法告诉浏览器应如何(当序列化为HTML时)序列化一个可以以多种方式序列化的属性。

( disabled="" is, last time I checked, invalid) (“ disabled=""是我上次检查的无效)

Try .replaceWith() 试试.replaceWith()

$('p').replaceWith(function (_, old) {
    return '<p disabled>' + old + '</p>';
});

fiddle Demo 小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM