如何将JS函数分配给使用循环生成的标签列表?
我的树枝文件中有一个循环:
{% for item in listItem %}
<h2 class="title" id="name-id"> ID {{ item.getRobotName() }}</h2>
<p id="latbot" data-lat="lat">{{ item.geteLat() }}</p>
<p id="lonbot" data-lon="lon">{{ item.getLon() }}</p>
{% endfor %}
在我的JavaScript文件中,
let h2 = document.getElementById("name-id");
h2.addEventListener("click", link);
function link() {
document.getElementById("name-id");
let thisLat = document.getElementById('latbot').getAttribute('data-lat');
console.log(thisLat);
let thisLon = document.getElementById('lonbot').getAttribute('data-lon')
console.log(thisLon);
let notifyIcon = L.divIcon({
className: 'notify-icon',
iconSize: [25, 25],
html: '<span></span>'
});
map.panTo([thisLat, thisLon]);
L.marker([thisLat,thisLon], {icon: notifyIcon}).addTo(map);
}
linkToMarker();
我想为所有使用此循环生成的H2分配JS函数。我该怎么做?
只有第一个项目连接到JS功能,但其他项目不
感激您。
I have a loop in my twig file :
{% for item in listItem %}
<h2 class="title" id="name-id"> ID {{ item.getRobotName() }}</h2>
<p id="latbot" data-lat="lat">{{ item.geteLat() }}</p>
<p id="lonbot" data-lon="lon">{{ item.getLon() }}</p>
{% endfor %}
In my Javascript file I have:
let h2 = document.getElementById("name-id");
h2.addEventListener("click", link);
function link() {
document.getElementById("name-id");
let thisLat = document.getElementById('latbot').getAttribute('data-lat');
console.log(thisLat);
let thisLon = document.getElementById('lonbot').getAttribute('data-lon')
console.log(thisLon);
let notifyIcon = L.divIcon({
className: 'notify-icon',
iconSize: [25, 25],
html: '<span></span>'
});
map.panTo([thisLat, thisLon]);
L.marker([thisLat,thisLon], {icon: notifyIcon}).addTo(map);
}
linkToMarker();
I would like to assign a JS function to all the h2 that are generate with this for loop. How can I do that ?
Only the first item is connected to the JS function but not the others
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论