gpt4 book ai didi

javascript - 如何使用 JS 向添加的输入添加属性

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:55 25 4
gpt4 key购买 nike

我需要将添加到 DOM 中的“bad”类的每个复选框来获取“disabled”属性。外部代码添加了复选框,因此当我自己将复选框插入到 DOM 时,我无法添加 disabled 属性。

我该怎么做?

更新:我不知道这些复选框何时会被添加。场景相当复杂。

最佳答案

****更新代码**** - 请参阅底部的注释。

这里建议的 DOMNodeInserted 事件不是跨浏览器的,它在 ie < 9 中不可用,即使在 ie 9 中也是有问题的。

一个简单的跨浏览器解决方案是设置一个间隔,每 100 毫秒检查一次,是否所有类名“bad”的复选框元素都被禁用:

function CheckBadCheckboxes()
{
var elems = document.getElementsByTagName("input");
for (var i = 0; i < elems.length; i++) {
if (elems[i].type == "checkbox" && /\b(bad)\b/i.test(elems[i].className) && !elems[i].disabled) {
elems[i].disabled = true;
}
}
}
window.setInterval(CheckBadCheckboxes, 100);

此代码不需要您使用 jQuery。

还有另一个反对 DOMNodeInserted 的论点,它已被弃用并会降低网页的性能。 PetersenDidIt 在此处的评论中对此进行了解释:

DOMNodeInserted equivalent in IE?

@Anurag Note: The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. A new specification is under development with the aim of addressing the use cases that mutation events solves, but in more performant manner. Thus, this specification describes mutation events for completeness, but deprecates the use of both the MutationEvent interface and the MutationNameEvent interface.

DOMNodeInserted 的错误行为:

http://help.dottoro.com/ljmcxjla.php

Note that the DOMNodeInserted event is buggy in Internet Explorer 9, it is not fired when a node is inserted for the first time. See the examples below for details.

更新。

我已经更新了我的代码,之前我使用了 getElementsByClassName(),不幸的是,IE < 9 不支持它,我用 getElementsByTagName("input") 替换了它。

关于javascript - 如何使用 JS 向添加的输入添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com