是否可以使HTML元素属性不可变

Is it possible to make HTML element attributes immutable?

本文关键字:属性 不可变 元素 HTML 可以使 是否      更新时间:2023-09-26

如果我想使javascript对象的属性不可变,我可以使用Object方法,如defineProperties()defineProperty()freeze()。我的问题是,如何对 HTML 元素属性执行相同的操作?

我已经尝试了上述方法,虽然它们可以用来防止直接设置元素的属性(例如 elem.id = 'foo'; ),正如预期的那样,基础属性仍可以通过 setAttribute() 进行更改。

"不,这是不可能的"的答案是可以接受的,但我还没有遇到任何明确的声明。

您可以使用突变观察器来恢复旧的属性值。

new MutationObserver(callback)
    .observe(elem, {attributes: true, attributeOldValue: true});
function callback(mutations, observer) {
    var target = mutations[0].target;
    observer.disconnect();
    mutations.forEach(function(mutation) {
        target.setAttribute(mutation.attributeName, mutation.oldValue);
    });
    observer.observe(target, {attributes: true, attributeOldValue: true});
}

感谢@DoctorDestructo提出的涉及避免无限循环所必需的observer.disconnect的建议。