[英]JavaScript function in twig foreach
I have this code that has the phone number of different posters.我有这个代码,其中包含不同海报的电话号码。
{% for ad in ads %}
...
<a class="btn" onclick="showNumber()" id="showNumber"><span class="fa fa-phone"></span> View Phone Number</a>
<input id="phonenum" style="display: none;" type="text" value="{{ ad.user.phone }}">
...
{% endfor %}
and the Javascript function和 Javascript 函数
<script type="text/javascript">
function showNumber() {
document.getElementById('showNumber').innerHTML = document.getElementById('phonenum').value;
}
</script>
the above works and the input field shows correctly the different numbers of the posters when i change it to block.当我将其更改为阻止时,上述工作和输入字段正确显示了不同数量的海报。 But the problem is that the phone number of the first button on the first button shows regardless of which button i click.但问题是,无论我单击哪个按钮,第一个按钮上的第一个按钮的电话号码都会显示。 what else should i do there?我还应该在那里做什么?
IDs are meant to be unique, you're creating elements in a loop and giving them the same ID ( phonenum
), instead of IDs you should use class names and retrieve the appropriate element base on which anchor was clicked. ID 是唯一的,您在循环中创建元素并为它们提供相同的 ID ( phonenum
),而不是 ID,您应该使用类名并检索基于单击锚点的适当元素。 Here is an example:下面是一个例子:
{% for ad in ads %}
...
<a class="btn" onclick="showNumber(e)"><span class="fa fa-phone"></span> View Phone Number</a>
<input class="phonenum" style="display: none;" type="text" value="{{ ad.user.phone }}">
...
{% endfor %}
<script type="text/javascript">
function showNumber(e) {
e.target.innerHTML = e.target.parent.querySelector('.phonenum').value;
}
</script>
In this example, e.target
is the clicked anchor and I'm using e.target.parent.querySelector('.phonenum')
to retrieve the input associated with the anchor (I'm assuming they have the same parent element).在这个例子中, e.target
是点击的锚点,我使用e.target.parent.querySelector('.phonenum')
来检索与锚点关联的输入(我假设它们具有相同的父元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.