javascript - html中的空格影响js节点操作怎么办?

WBOY
Release: 2016-06-06 20:24:17
Original
1359 people have browsed it

<code>  
<title>DOM Test</title>  
  
<table>   
    <tr>   
    <td id="TEST">  
        <input type="submit" value="确定">  
        <input type="button" value="取消">  
    </td>  
    </tr>   
</table>  
  
<script type="text/javascript">  

    var td = document.getElementById("TEST");  
    alert(td.childNodes.length);    //结果为4   

</script>  
  
  
 </code>
Copy after login
Copy after login

类似的还有节点操作等,由于元素书写时存在空白换行符等,所以导致在操作DOM节点出现问题?

问一下,这个问题怎么解决呢?

将html代码压缩,但是好多网站都没有压缩啊?到底怎么解决呢?

谢谢了!

回复内容:

<code>  
<title>DOM Test</title>  
  
<table>   
    <tr>   
    <td id="TEST">  
        <input type="submit" value="确定">  
        <input type="button" value="取消">  
    </td>  
    </tr>   
</table>  
  
<script type="text/javascript">  

    var td = document.getElementById("TEST");  
    alert(td.childNodes.length);    //结果为4   

</script>  
  
  
 </code>
Copy after login
Copy after login

类似的还有节点操作等,由于元素书写时存在空白换行符等,所以导致在操作DOM节点出现问题?

问一下,这个问题怎么解决呢?

将html代码压缩,但是好多网站都没有压缩啊?到底怎么解决呢?

谢谢了!

childNodes会把文本节点也获取了, input前后都有个文本节点。
你可以用td.children.length来获取元素节点的个数,这样就对了

你用错方法了

<code class="js">td.childElementCount</code>
Copy after login

这是正常现象,浏览器在解析节点中空白符时,会把它当作文本节点,所以在遍历子节点时应该对文本节点做特殊处理,可以利用Document类型的nodeType属性过滤文本节点:

<code>var td = document.getElementById("TEST");  
var childs=[],i,len,node;
for(i=0,len=td.childNodes.length;i<len node="td.childNodes[i];" if childs.push alert></len></code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!