JavaScript在Django模板中找不到ID

时间:2019-11-25 13:28:47

标签: javascript django

我正在使用Django开发应用程序,并且我有这个feed.html模板,可以加载不同的部分:

    <div class="container">
       <div class="row">
           {% for piece in pieces %}
                {% include "pieces/pieces_card.html" %}
           {% endfor %}
       </div>
    </div>

在此pieces_card.html中,我想加载执行3D可视化的脚本。我已完成下一件事:

<div class="madeleine container" id="id-{{ piece.id }}"></div>

问题是JS脚本失败,它显示此错误MADELEINE[ERR] Target must be a valid DOM Element.。 我认为这是因为它是在加载选定ID之前加载的,那么如何才能等到此特定元素准备好了?

这是JS

function showPiece(targ, piece){
    window.onload = function(targ, piece){
        Lily.ready({
                target: targ,  // target div id
                file: 'files',  // file input id
                path: '../../static/js/src', // path to source directory from current html file
        });
    };


    window.onload = function(targ, piece){
            var madeleine = new Madeleine({
                target: targ, // target div id
                data: piece,
                path: '../../static/js/src', // path to source directory from current html file
            });
    };
};

pieces_card.html中:

var url_objetivo = '{{ piece.file.url }}'
    console.log("==== " + url_objetivo)
    var id_objetivo = "id-" + {{ piece.id}}
    console.log("==== " + id_objetivo)

    showPiece(targ=id_objetivo,
                        piece=url_objetivo)

1 个答案:

答案 0 :(得分:1)

更新:

targ删除piecewindow.onload args

window.onload = function(){ ... }

上一个答案:

此JS函数参数语法无效:

showPiece(targ=id_objetivo, piece=url_objetivo)

尝试

showPiece(id_objetivo, url_objetivo)