开发者

Javascript jquery for loop problem

When i run this for loop it gives me the name bob and for jacob it says undefined does anyone have any idea why?

        $(function(){

        count = 1;

        for(x=0; x <= count; x++)
        {
            track = $('#track' + x).val();
         开发者_高级运维   document.write(track);
        }

    });

    <input type="hidden" id="track0" value="bob" /> 
<input type="hidden" id="track1" value="jacob" />   


Writing to document deletes your previous HTML. So , you cannot access the element by id anymore. Alerting or writing it to some div instead of document gives proper response.

http://jsfiddle.net/KjHFM/

<span id='test'> RESULT : </span>


 $(function(){

    count = 1;

    for(x=0; x <= count; x++)
    {
        track = $('#track' + x).val();
        alert(track); // or $('#test').append(track+ "    ");
    }


});


Because document.write() replaces old html, it means that track1 is deleted with first .write()

Works here with alert

<script>        $(function(){

        count = 1;

        for(x=0; x <= count; x++)
        {
        $("#content").append(x+' is '+$('#track' + x).val());
        }

    });</Script>
<div id="content"></div>
<input type="hidden" id="track0" value="bob" /> 
<input type="hidden" id="track1" value="jacob" />  


The first time you call document.write you are replacing the dom with the html text bob

When the second iteraction runs in the for loop jacob is not in the dom anymore - this is why undefined is written.

Also as you are not using the var keyword x, count and track are now all global variables of the window object.


document.write() alters the DOM in a very agressive way, replacing the original content.

Correct jQuery notation would be:

jQuery(function($){
    $("input").each(function( index ){
        alert( index + ': ' + $(this).get(0).id + ' = ' + $(this).val() );
    });
});

You could add the text you're now seeing in the alert boxes to the body by replacing the alert line with the following:

$("body").append( index + ': ' + $(this).get(0).id + ' = ' + $(this).val() );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜