如何将JS函数分配给使用循环生成的标签列表?

发布于 2025-01-27 07:14:00 字数 1192 浏览 1 评论 0原文

我的树枝文件中有一个循环:

{% 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文