在pageload上从迭代对象调用JS函数



晚上好,我想通过Javascript动态设置进度条,将宽度值替换为计算的百分比。我使用Postgres数据库运行Django。现在我可以通过JS函数来设置样式,但如何在页面加载时触发函数呢?

通过该视图,我可以传递迭代对象的相关票数(poll_product(和总票数。我想把这两个作为参数传递给我的JS函数,这样我就可以计算百分比并设置它

我希望我解释得足够清楚,但请不要问我需要详细说明的任何问题。

{% for poll_product in poll_product_list %}
<form action="{% url 'add_vote' poll_product.id %}" method="POST">
{% csrf_token %}
<div class="row mt-1">
<div class="col-8">
<h5>{{ poll_product.product_type }} : {{ poll_product.votes }}</h5>
</div>
<div class="col-4">
{% if user.is_authenticated and not voted %}
<input type="submit" class="btn-sm btn-dark" value="Vote">
{% endif%}
</div>
/* ------------ below is the relevant part ---------------- */
<div class="col-6 progress">
<div id="{{poll_product.id}}" class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100" ></div>
<script>setProgressBar('{{poll_product.votes}}', '{{total_votes}}', '{{poll_product.id}}');</script>
</div>
</div>
<input type="hidden" name="redirect_url" value="{{ request.path }}">
</form>
{% endfor %}

通过调用以下函数解决了这个问题:

function setProgressBar(productVotes, totalVotes, productID) {
progressPercentage = Math.round(productVotes/totalVotes * 100);
document.getElementById(productID).style.width = progressPercentage+"%";
} 

在HTML 中为函数调用编辑了OP中的代码

最新更新