Javascript chrome和css问题
我有这个html代码Javascript chrome和css问题,javascript,css,google-chrome,prototypejs,Javascript,Css,Google Chrome,Prototypejs,我有这个html代码 <div id = 'status'> <span class="formw" style="background-color:#FBD9E5;"> some text </span> </div> chrome抛出以下错误: Uncaught TypeError: Cannot read property 'style' of null 有人知道原因吗 更新:我正在使用Prototype。试试看 $('#status')
<div id = 'status'>
<span class="formw" style="background-color:#FBD9E5;">
some text
</span>
</div>
chrome抛出以下错误:
Uncaught TypeError: Cannot read property 'style' of null
有人知道原因吗
更新:我正在使用Prototype。试试看
$('#status').style.backgroundColor = '#99e83f';
如果您正在使用jquery,请尝试以下方法
$('#status').css('background-color','green');
这应该是可行的中有两个错误:
$('status').style.backgroundColor = '#99e83f';
第一名:
$('#status')[0].style.backgroundColor = '#99e83f';
('#status').css('background-color','#99e83f');
- 您缺少用于在状态div的选择器中指定id的
$('#status')[0].style.backgroundColor = '#99e83f';
('#status').css('background-color','#99e83f');
属性在style
的jQuery对象上不起作用$(“#状态”)
解决方案:
$('#status')[0].style.backgroundColor = '#99e83f';
('#status').css('background-color','#99e83f');
方法一:
$('#status')[0].style.backgroundColor = '#99e83f';
('#status').css('background-color','#99e83f');
上面添加的[0]
将jQuery对象转换为普通DOM元素,以便成功应用style
属性
方法二:
$('#status')[0].style.backgroundColor = '#99e83f';
('#status').css('background-color','#99e83f');
当您使用经典的DOM方法时,在原型中的元素有时会出现一些DOM问题 而是使用prototype中定义的方法来读取和设置元素的样式 您感兴趣的两种方法是:
- .setStyle,文档()
- .getStyle,文档()
$('status').setStyle( { 'background-color' : '#99e83f' } );
$('status').getStyle( 'background-color' )
如果要读取属性,可以使用:
$('status').setStyle( { 'background-color' : '#99e83f' } );
$('status').getStyle( 'background-color' )
对于jquery群组,$('element_id')是document.getElementById('element_id')的等效缩写。如果您想通过选择器获取元素,那么它应该是$$(“#element_id”).first()。您特别提到了Google Chrome。Chrome对标准的要求比大多数标准都严格,尤其是当您的文档具有DOCTYPE时 标记
让我怀疑。尽管大多数浏览器对常见的语法错误都是宽容的,但通过将id
空格与equals分隔,可能会将其视为布尔属性,这相当于
您可以打开javascript控制台(Shift+Ctrl+J)进行测试,并查看键入的结果:
$('status')
$('id')
要获得解决方案,请尝试以下方法:
<div id="status">
@用户,我们是否有名为backgroundcolor fordiv的属性,它应该是正确的颜色或背景图像URL我相信您在
ID
中缺少一个
,请执行:$(“#status')
,我假设您在这里使用jQuery。@gov-是的,该属性有效@用户-这是否适用于document.getElementById()?@steve,你是对的,我忘了。如果是jQuery,那么.style.foo
也是错误的(它会抱怨style
为空,而不是$
的返回值为空。(mutter,mutter,$
是一个讨厌的变量名:)。我猜,$
直接映射到了document.getElementById
,JS在源代码中出现div之前就已经运行了,但是问题是缺少了太多的信息,这只是盲目地乱翻。@jakub,在jquery中正确的做法是.css方法(语法),上面的大多数答案都没有使用它,但为什么我的答案被标记下来。为什么你认为它不是选择器?我不明白。编辑:算了吧,我刚刚找到你对此的评论。@sarfraz,我很久以前给过你的解决方案,但不知道他是否尝试过。@gov:你在我的答案之后编辑了你的答案::)@萨弗雷斯……嗯,我忘了between@gov:没问题这就是问题所在:)“上面添加的[0]将jQuery对象转换为普通DOM元素”,谢谢,+1。