用JavaScript往web文档中空元素填入空白符
Web 文档的结构如下:
<h6>起身椅</h6> <p class="intro">风格为现代风格,材质为仿皮布,可以展开和收缩,展开的尺寸:长1.7米,宽0.73米,高0.57米</p> <h6>起身椅</h6> <p class="intro"></p>
JS程序的代码如下:
if(!document.getElementsByTagName) return;
var ps=document.getElementsByTagName('p');
var pIntroClass, pIntroValue;
for(var i=0;i< ps.length;i++)
{
pIntroClass = ps[i].className;
if (ps[i].firstChild == null)
{
pIntroValue = ps[i].nodeValue;
}
else
{
pIntroValue = ps[i].firstChild.nodeValue;
}
if(pIntroClass.indexOf('intro')!=-1 && pIntroValue==null)
{
pIntroValue=' ';
}
}
步骤如下:
(1)if(!document.getElementsByTagName) return;
进行对象检测
(2)document.getElementsByTagName('p')
获取 p 标签这个元素所有数组集合
(3)for(var i=0; i<ps.length; i++)
for循环遍历 ps。ps[i] 是document.getElementsByTagName('p')中的第i个对象,在上面p的子节点可能是文本节点,在调试过程中发现也可以不是。我们就对它进行判断看看是不是:class含有intro并且它的节点值为 null 的p元素往里面填入空白符 。
注:更新于:2009年12月23日。以前的:http://bbs.blueidea.com/thread-2803376-1-1.html
浙公网安备 33010602011771号