我的循环怎么了?

时间:2013-04-25 02:15:57

标签: javascript html jquery jquery-mobile

XML响应:

<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
    <Code>106377</Code>
    <Name>Blackened red snapper</Name>
    <Category>123</Category>
    <Yield>4</Yield>
    <YieldUnit/>
</Table>
<Table diffgr:id="Table2" msdata:rowOrder="1">
    <Code>303570</Code>
    <Name>Celery soup</Name>
    <Category>123</Category>
    <Yield>1</Yield>
    <YieldUnit/>
</Table>
<Table diffgr:id="Table3" msdata:rowOrder="2">
    <Code>303675</Code>
    <Name>Challah French Toast</Name>
    <Category>123</Category>
    <Yield>6</Yield>
    <YieldUnit/>
</Table>
<Table diffgr:id="Table4" msdata:rowOrder="3">
    <Code>303681</Code>
    <Name>Challah french toast</Name>
    <Category>123</Category>
    <Yield>4</Yield>
    <YieldUnit/>
</NewDataSet>

HTML代码

<div data-role="output">
    <ul id="RecipeList" data-role="listview" data-split-icon="star" data-split-theme="e" data-inset="true">
    </ul>
</div>

JS代码

var CodeObj = new Array();
var NameObj = new Array();
var Codeindex = 0;
var Nameindex = 0;

$(req.responseText).find('Name').each(function () {
    NameObj[Nameindex] = $(this).text();
    Nameindex += 0;

    for (var i = 0; i < NameObj.length; i++) {
        $(this).append(NameObj[i] + "<br/>");

        $(req.responseText).find('Code').each(function () {
            CodeObj[Codeindex] = $(this).text();
            Codeindex += 0;
            for (var a = 0; a < CodeObj.length; a++) {
                $(this).append(CodeObj[a] + "<br/>");
            }
        });

        var $content = $('<li><a href="#"><img src="../../img/album-bb.jpg"><h3>Name: ' + NameObj[i] + '</h3><p>Code: ' + CodeObj[a] + '</p></a><a href="#purchase" data-rel="popup" data-position-to="window" data-transition="pop">Add to favorites</a></li>');
        $('#RecipeList').append($content).listview('refresh');
    }
});

Listview输出

Name : Blackened red snapper
Code : 106377
Name : Celery soup
Code : 106377
Name : Challah french toast
Code : 106377
Name : Challah french toastr
Code : 106377

问题:始终是相同的代码。任何人都知道我的循环有什么问题吗?谢谢。我尝试了很多方法。但仍然可以为Name

获得正确的输出

3 个答案:

答案 0 :(得分:1)

问题在于增量。替换:

Nameindex +=0;
Codeindex +=0;

使用

Nameindex++;
Codeindex++;

Nameindex +=1;
Codeindex +=1;

答案 1 :(得分:0)

似乎

  

Nameindex + = 0;   Codeindex + = 0;

错了。不应该是Nameindex + = 1吗?

答案 2 :(得分:0)

Nameindex += 0Codeindex += 0是无操作的,所以他们可能与它有关。

相反,试试这个:

$(req.responseText).find("Table").each(function() {
    var item = $(this),
        name = item.find("Name").text(),
        code = item.find("Code").text();
    $("#RecipeList").append('<li><a href="#"><img src="...." />'
       +'<h3>'+name+'</h3>Code: '+code+'</a>.....');
});