1

Its very strange condition for me but anchors.length only give total number of anchors when i place script after all anchors tag and when i place before all anchors it gives zero....so i did this but now function lngt() is not returning length of anchors please help me i just stuck..

here is my code

<div class="box">
 <script>
 var na;
 na = lngt();
 for(i = 0 ; i < na ; i++)
{
    txt = document.anchors[i].innerHTML;
    lnk = document.anchors[i].name;
    document.write( "<a href='#"+lnk+"'>"+ txt + "</a></br>");
 }
 </script>
 </div>


<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
     <br/><br /><br/><br/><br/>
<a name="a">anchor 1</a><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br   
/><br/><br/><br/>
<a name="b">anchor 2</a><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br 
/><br/><br/><br/>
<a name="c">anchor 3</a><br/>

<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br
/><br/><br/><br/>
<a name="d">anchor 4</a><br/>


<script>
function lngt(){
var nc = document.anchors.length;
return nc;
}
</script>

When i put both script at the end its working fine :/ Thanks in Advance :)

4

2 回答 2

2

Working jsFiddle Demo

  • Wait for your elements to load (use DOM ready, or window.onload, or add the script tag after your HTML elements).
  • Use innerHTML to put new elements in your page.

<script>
window.onload = function () {
    var anchors = document.anchors;
    var toc = document.getElementById('toc');
    for (var i = 0, l = anchors.length; i < l; i++) {
        toc.innerHTML += '<div><a href="#' + anchors[i].name + '">' + anchors[i].innerHTML +'</a></div>';
    }
};
</script>

<div id="toc"></div>

<a name="a">anchor 1</a>
<a name="b">anchor 2</a>
<a name="c">anchor 3</a>
<a name="d">anchor 4</a>
于 2013-06-21T15:11:03.703 回答
0

You're calling the function (in the upper <script> block) before the elements exist.

于 2013-06-21T14:57:46.773 回答