javascript - 将python对象绑定到html按钮
问题描述
我有一个创建按钮列表的python字典,即
recipes = {0 : {'name' : 'Chicken Ticka', 'products' : products_dict, 'instructions' : 'this are the instructions'},
1 : {'name' : 'Beef Masala', 'products' : products_dict_2, 'instructions' : 'this are the instructions for 2'}}
在 HTML 中:
{% if recipes is not none%}
{% for key, value in recipes.items() %}
<button type="button" class="btn btn-light btn-block">{{value['name']}}</button>
{% endfor %}
{% endif %}
我想根据按下的按钮以某种方式更新(通过刷新或动态)页面。
我知道如何将按钮附加到 JS 函数,但是如何将该函数与相应的对象附加?
解决方案
这不完全是我想到的方法,但我设法获得了我想要的功能:
字典示例:
products_dict = {0 : {'name' : '123', 'count' : '234'},1 : {'name' : '345', 'count' : '456'},2 : {'name' : '567', 'count' : '678'}}
products_dict_2 = {0 : {'name' : 'bbb', 'count' : 'qwe'},1 : {'name' : 'wer', 'count' : 'ert'},2 : {'name' : 'rty', 'count' : 'tyu'}}
recipes = {0 : {'name' : 'Chicken', 'products' : products_dict, 'instructions' : 'this are the instructions'},
1 : {'name' : 'Beef', 'products' : products_dict_2, 'instructions' : 'this are the instructions for 2'}}
按钮创建:
{% if recipes is not none%}
{% for key, recipe in recipes.items() %}
<button id={{key}} onclick="uploadRecipe({{recipe}})" type="button" class="btn btn-light btn-block">{{recipe['name']}}</button>
{% endfor %}
{% endif %}
和uploadRecipe函数
<script>
function uploadRecipe(recipe) {
products = recipe['products'];
var table = document.getElementById("recipeProducts").getElementsByTagName('tbody')[0];
$("#recipeProducts tbody tr").remove();
for (var prop in products) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = products[prop]['name'].bold();
cell2.innerHTML = products[prop]['count'].bold();
}
document.getElementById("recipe_instructions_text").innerHTML = recipe['instructions'];
}
</script>
推荐阅读
- javascript - 识别组件的嵌套位置
- python - 正则表达式:根据标点符号断开字符串
- typescript - 使用带有 split() 的正则表达式只是为了在字符串中获取全名
- android - 如何在 Espresso 测试中单击 Android 10 中的“从剪贴板”弹出窗口?
- android - 深度链接屏幕自动返回上一个屏幕 - ReactNative Android
- r - 使用 mutate 和 case_when 创建二分法 var (0/1) 的函数
- nginx - 使用 certbot 通配符生成 https
- flutter - 颤振:流提供者
onAuthStateChanged 总是返回 null 作为第一个值 - mongodb - 将字符串数组转换为 db ref 数组
- php - PHP:来自图像字节的图像 mime 类型