jQuery append()意外行为

时间:2015-12-29 14:16:30

标签: javascript php jquery

以下是我要获取的数组示例:

[
    {"code":"001","name":"FOO","icon":"foo.png","price":3.5},
    {"code":"002","name":"BAR","icon":"bar.png","price":4.5}
]`

我必须填写的DOM看起来像:

<div class="container" style="margin-top:0;">     
    <ul id="#list">     
    </ul>
</div>

填写所有内容的JS代码是:

function exampleGet() {

$.getJSON("/myfile.json", function(jsonResponse) {

    var counter = 0,
        content = '',
        listStart = '<li><div class="slide"><table class="spoon"><tr>',
        listEnd = '</tr></table></div></li>',
        columnStart = '<td><div class="spoon-banner"><ul>',
        columnEnd = '</ul></div></td>';     

    for (i = 0; i < jsonResponse.length; i++) {

        var lStart = '',
            lEnd = '',
            // string that contains HTML and array values, accessed
            // by: jsonResponse[i].key
            colContent = [...string with HTML...]

        // makes sure to group everything 4 by 4
        if(counter === 0) {  
            lStart = listStart;
        }                                                                      
        // makes sure to group everything 4 by 4
        if(counter === 3) {
            lEnd = listEnd;
            counter = -1;
        }

        // use an unique string for all changes
        content = content.concat(lStart,columnStart,coinLogo,coinData,columnEnd,lEnd);                        
        counter++;
    };

    $('#list').append(content);
});
}

RESULT

&#34; respose&#34; Mozilla Developers Tools的选项卡显示(显然)随机字符串(见下文),并且不对DOM应用任何更改。

[...] Wghjd7siYfkshbfbybjowLCJ1c2VycyI09u99XQ [...]

BUT

如果我在content中打印字符串console.log(),字符串看起来很完美!所以问题必须在$('#list').append(content);

注意

1)函数exampleGet()$(document).ready(function(){[...]})封装到我的HTML页面的<script>中。

2)我正在使用PHP内置服务器进行测试(我第一次使用它)

2 个答案:

答案 0 :(得分:2)

在html中使用

<ul id="list">

而不是

<ul id="#list">    

答案 1 :(得分:0)

您必须将id=#list更改为id=list

<div class="container" style="margin-top:0;">     
    <ul id="list">     
    </ul>
</div>