【发布时间】:2016-04-04 02:16:01
【问题描述】:
我创建了一个简单的库,并尝试更改库中元素的样式。很简单的事情。
content[0].removeChild(content[0].firstElementChild);
content[0].style.backgroundColor = 'green';
我在 Chrome 中尝试过,它就像一个魅力。然后我在 Microsoft Edge 和 Internet Explorer 中对其进行了测试,它们都无法识别我要更改的元素。
他们给出以下错误:
无法获取未定义或空引用的属性“removeChild”
我该如何解决这个问题,以便它在所有浏览器中都能正常工作?
function veryUsefullLibrary(parentElem) {
var outerWrapper = document.createElement('div'),
innerWrapper = document.createElement('div'),
content = parentElem.children;
function changeFunction(e) {
console.log(content);
content[0].removeChild(content[0].firstElementChild);
content[0].style.backgroundColor = 'green';
}
while (content.length)
innerWrapper.appendChild(content[0]);
content = innerWrapper.children;
var radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'simSlider';
radio.addEventListener('change', changeFunction);
parentElem.appendChild(radio);
outerWrapper.appendChild(innerWrapper);
parentElem.appendChild(outerWrapper);
}
var overall = document.getElementById('overall'),
lib = new veryUsefullLibrary(overall);
#first {
width: 500px;
height: 386px;
}
<div id="overall">
<div class="content" id="first">
<img src="https://verkoren.files.wordpress.com/2013/05/junk-dump-22918.jpg" />
</div>
</div>
【问题讨论】:
-
我认为 jQuery 不是一个选项?
-
@staypuftman 如果这是唯一的方法,我会使用 JQuery,但我非常怀疑纯 JavaScript 不可能
-
是的,我确信有办法。只是我的经验是,如果你依赖纯 JS,你经常会遇到这样的问题。
-
@staypuftman 我明白了。我会记住这一点!谢谢!
标签: javascript internet-explorer microsoft-edge