在Flask中使用动态生成的jQuery绑定事件失败

时间:2017-02-13 17:18:04

标签: jquery flask

问题

我根据数据库值在HTML中动态创建按钮。我想使用动态生成的jQuery将这些按钮绑定到事件。我已经从SO中读到了很多关于使用jQuery进行动态事件绑定的Q / A,但我仍然失败了(例如:Event binding on dynamically created elements?)。这让我想知道Flask / jinja生成的HTML是否会导致问题?

模板

<div class="buttons">
    {% for lvl in lvls %}
    <button id="btn_{{ lvl.descriptor }}">{{ lvl.descriptor }}</button>
    {% endfor %}
</div>

<script type="text/javascript">

    $(document).ready(function() {
        # Some code here
    });

    {% for lvl in lvls %}
    $('.buttons').on('click', '#btn_{{ lvl.descriptor }}', function() {
        alert("Button clicked!");
    });
    {% endfor %}

</script>

HTML

<div class="buttons">
    <button id="btn_Level 1">Level 1</button>
    <button id="btn_Level 2">Level 2</button>
    <button id="btn_Level 3">Level 3</button>
</div>

<script type="text/javascript">

    $(document).ready(function() {
        # Some code here
    });

    $('.buttons').on('click', '#btn_Level 1', function() {
        alert("Button clicked!");
    });

    $('.buttons').on('click', '#btn_Level 2', function() {
        alert("Button clicked!");
    });

    $('.buttons').on('click', '#btn_Level 3', function() {
        alert("Button clicked!");
    });

</script>

1 个答案:

答案 0 :(得分:0)

ID中的空格无效HTML:

See this SO Post for more info

摆脱空间,它应该工作。

相关问题