【问题标题】:Appending elements to a DIV from a JSON array in Polymer从 Polymer 中的 JSON 数组将元素附加到 DIV
【发布时间】:2015-01-11 00:59:37
【问题描述】:

我现在正在努力将一组 div 插入到 Polymer 的纸阴影内的核心标题面板中。我从 JSON 数组中获取一组值,我需要为每个值创建一个包含 HTML 内容(最终是复选框)的 div。这是相关的sn-p代码:

<paper-shadow class="card upload-options-box" z="1">
    <core-header-panel flex id="graphHeaderList">
        <core-toolbar class="upload-option-header">
            <span flex>Variable</span>
        </core-toolbar>
        <core-label horizontal layout> // this is all just an example of what I eventually want to insert
            <paper-checkbox for></paper-checkbox>
            <div vertical layout>
                <h4>MakeCircuitCreated</h4>
            </div>
        </core-label> // end of example of insert
    </core-header-panel>
</paper-shadow>

和 JQuery:

function addHeaders(){
    $.getJSON('http://myURL/getDataHeaders', function(data) {
        var headerArray = [];
            $.each(data, function(key, val) {
                $('#graphHeaderList').append("<div id='" +val +"'></div>");
                console.log(val);
                headerArray.push(val)
            });
            console.log(headerArray);
        });
    }
        window.onload = addHeaders; //grabs the header values when the page is loaded

我的 JSON:

{
"headers": [
    "MakeSpawnFish",
    "MakeEndGame",
    "MakeModeChange",
    "MakeConnectComponent",
    "MakeCircuitCreated",
    "MakeStartGame",
    "MakeSnapshot",
    "MakeResetBoard",
    "MakeAddComponent",
    "MakeCaptureFish",
    "MakeRemoveComponent",
    "MakeDisconnectComponent"
]
}

【问题讨论】:

  • 您收到的错误信息是什么?
  • 没有错误消息,但没有附加任何内容
  • 生成的html中基本上什么都没有显示
  • 你想用 jquery 还是用聚合物来做这个?我不认为这两者配合得很好。老实说,如果使用聚合物,我认为不需要 jquery。我推荐 core-ajax 和一个重复模板 polymer-project.org/docs/elements/core-elements.html#core-ajax
  • 嘿 Jimi - 好像最近每次我遇到问题时你都会来帮助我;)我倾向于同意你的观点,因为我能够使用非聚合物
    它工作得很好。我将尝试使用 core-ajax,因为演示似乎可以满足我的需要,但稍后您可能会看到另一个关于它的问题

标签: javascript jquery html polymer


【解决方案1】:

在我看来,您的 $.each 调用错误。

在您的 json 文件中,您有一个名为 headers 的密钥。当您的每个函数迭代时,它会获得 1 个键并将其成员(一个数组)添加到 div。我对其进行了测试,并得到了一个包含每个成员的 div,因为它是 id!

所以你可能需要在内部数组上嵌套一个要调用的每个函数

$.each(data, function(key, val) {
    $.each(val, function(index,value){
        $('#graphHeaderList').append("<div id=" + "'" + value + "'"  + "></div>");
          console.log(value);
          headerArray.push(value);
    }
);

https://api.jquery.com/jquery.each/

【讨论】:

  • 这绝对让我更接近 - 但仍然没有任何内容出现在 html 中。无法弄清楚为什么 .append 似乎没有附加到 #graphHeaderList
【解决方案2】:

您的代码:

$('#graphHeaderList').append("<div id='" +val +"'></div>");

不起作用,因为 jQuery 无法在其范围内找到该元素。但是,polymer 会通过其automatic node finding 功能自动创建 id 元素引用:

this.$.graphHeaderList

所以如果你使用它应该可以按预期工作:

$(this.$.graphHeaderList).append("<div id='" +val +"'></div>");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多