[英]How to pass parameter to javascript from Django template while using for loop
I am creating a quiz application using django.我正在使用 django 创建一个测验应用程序。 I am facing a problem in sending paramter to my javascript function from django template.
我在从 django 模板向我的 javascript function 发送参数时遇到问题。
Html Code. Html 代码。
{% for qts in page %}
<input type="button" id ="btn-1" name="grp" value="{{qts.opt1}}" class="btn btn-outline-primary mt-3" onclick = "check(this,{{qts.answer}})">
Javascript Code Javascript 代码
function check(btn,answer) {
var user_ans_id = btn.id;
var user_ans = document.getElementById(user_ans_id).value;
console.log(answer);
}
Is there any other solution.有没有其他解决办法。
Thanks in Advance!提前致谢!
A simpler and cleaner way of achieving the desired output can be implemented as follows using jquery实现所需 output 的更简单和更清洁的方法可以使用 jquery 实现如下
{% for qts in page %}
<input type="button" value="{{qts.opt1}}" class="quest-btn" data-answer="{{qts.answer}}" />
{% endfor %}
<script>
$(".quest-btn").click((e) => {
const targetElement = e.target;
console.log(
targetElement.dataset.answer,
targetElement.value
);
});
</script>
In the about code quest-class is just a dummy class to attach click event listener to multiple button you can use any common class in buttons.在 about code quest-class 中只是一个虚拟 class 将点击事件侦听器附加到多个按钮,您可以在按钮中使用任何常见的 class。
to know more about jquery click event listener check this out要了解有关 jquery 单击事件侦听器的更多信息,请查看此
for more info about data-attributes check this有关数据属性的更多信息,请查看此
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.