gpt4 book ai didi

javascript - 如何在 twig 循环内打印 JS 函数的结果

转载 作者:行者123 更新时间:2023-12-02 21:34:59 24 4
gpt4 key购买 nike


我有两个 Twig 变量。我需要将它们传递给我的js函数travelTime()并在html标签中返回结果。
这是代码。这是行不通的:

{% for item in trains %}
<div class="trainShedule">
<div class="container">
<div class="row">
<div class="col-12">
<div id="trainShedule-timeTravel">
{% block javascripts %}
<script> travelTime('{{ item.departure.time }}', '{{ item.arrival.time }}' </script>
{% endblock %}
</div>
</div>
</div>
</div>
{% endfor %}

<script>
function travelTime(firstTime, secondTime){
let getDate = (string) => new Date(0, 0,0, string.split(':')[0], string.split(':')[1]);
let different = (getDate(secondTime) - getDate(firstTime));
let hours = Math.floor((different % 86400000) / 3600000);
let minutes = Math.round(((different % 86400000) % 3600000) / 60000);
let result = hours + ':' + minutes;
$(this)[0].innerHTML = result;
}
</script>

最佳答案

首先,您需要渲染清晰的 html,而不在代码中实现任何 javascript。

将变量传递给 twig 循环中的 html-node attrs 并删除节点的 id,使用类,如下所示:

 {% for item in trains %}
<div class="trainShedule">
<div class="container">
<div class="row">
<div class="col-12">
<div class="data_output" data-departure="{{ item.departure.time }}" data-arrival= "{{ item.arrival.time }}"></div>
</div>
</div>
</div>
</div>
{% endfor %}

然后像这样改进 ypur js:

<script>
//you don't need params in your functions, we need to get data other way..
function travelTime(){
//collect nodes you want to add value
let dataNodes = document.getElementsByClassName('data_output');

//loop over dataNodes
for(let i = 0; i < dataNodes.length; i++){

//get current values for this node
let departure = dataNodes[i].dataset.departure;
let arrival = dataNodes[i].dataset.arrival;

//here you do your mathematics stuff
//.... result..

//finally pass data to html-node
dataNodes[i].innerHTML = result;
}
}

//don't forget to call function!
travelTime();
</script>

关于javascript - 如何在 twig 循环内打印 JS 函数的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60521641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com