本文介绍了无效的分配左侧与三元if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个这样的样式表:

I want to create an stylesheet like this:

var sheet = document.createElement('style'); sheet.type = 'text/css';
sheet.innerHTML = data.style;

但 IE需要自己的语法。为了简化的代码,我试过了

But it seems that IE needs its own syntax. To simplify this answer's code, I have tried

var sheet = document.createElement('style'); sheet.type = 'text/css';
(sheet.styleSheet ? sheet.styleSheet.cssText : sheet.innerHTML) = data.style;

但抛出 ReferenceError:左侧无效分配

然后,我必须使用...

Then, must I use...

var sheet = document.createElement('style'); sheet.type = 'text/css';
if(sheet.styleSheet) sheet.styleSheet.cssText = data.style;
else sheet.innerHTML = data.style;

...还是有更简单的选择?

... or is there a simpler alternative?

推荐答案

您可以随时执行:

sheet.styleSheet ? sheet.styleSheet.cssText = data.style 
                 : sheet.appendChild(document.createTextNode(data.style));

这篇关于无效的分配左侧与三元if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:53