我有一个有效的解决方案,但我想知道最好的方法.
我有一个模板,生成一个像这样的项目表:
{% for item in item_list %}
{{ item.name }}: <button onclick="doSomething({{item.id }})">Click Me!</button>
{% endfor %}
<script>
function doSomething(item_id) {
// Do stuff here
// Is actually an ajax request which sends the item's id
}
</script>
Run Code Online (Sandbox Code Playgroud)
这很好用,但是我知道在Javascript中使用监听器是最好的做法,而不是onlick.
有一个函数并item.id根据单击的按钮动态注入函数的最佳方法是什么?
我能想到的唯一方法是item_list在Javascript中再次循环并为每个item按钮创建一个函数.这是最好的方法吗?
{% for item in item_list %}
{{ item.name }}: <button id="btn-{{ item.id }}">Click Me!</button>
{% endfor %}
<script>
{% for item in item_list %}
jQuery("#btn-{{ item.id }}").click(function() {
// Do …Run Code Online (Sandbox Code Playgroud)