简体   繁体   English

如何使用 JavaScript 添加指向元素的链接?

[英]How do I add link to an element with JavaScript?

So instead of directly using tag in each element, is there a way to add the tag dynamically?所以不是直接在每个元素中使用标签,有没有办法动态添加标签?

What I'm trying to do is that first I have a calendar, and when a user clicks a particular date on the calendar, the user can see what happened in that date at a separate page.我要做的是首先我有一个日历,当用户单击日历上的特定日期时,用户可以在单独的页面上看到该日期发生的事情。
The thing is that I'm using django-scheduler library, so the calendar is pre-desiged, meaning I cannot directly make changes to the code.问题是我正在使用django-scheduler库,所以日历是预先设计的,这意味着我不能直接更改代码。 All I have in my template is {% calendar %} .我的模板中只有{% calendar %} So I figured I'd have to control using JavaScript.所以我想我必须使用 JavaScript 进行控制。

Here's what I see in the 'source' of the page:这是我在页面的“来源”中看到的内容:

...
<div class="content" data-date="2020-05-27"></div>
<div class="content" data-date="2020-05-28"></div>
<div class="content" data-date="2020-05-29"></div>
...

For each data-date , I want to add link which looks like: www.some-webpage.com/2020-05-27对于每个data-date ,我想添加如下所示的链接:www.some-webpage.com/2020-05-27

Is it ever possible to do this with JavaScript?有没有可能用 JavaScript 做到这一点? Thanks in advance.提前致谢。 :) :)

You can add the function below in the onClick of the button.您可以在按钮的onClick下面添加function。 Here I am using document.querySelectorAll to select all elements with data-date attribute and then looping over each element to form an a tag with link based on the data-date attribute.在这里,我使用document.querySelectorAll到 select 所有具有data-date属性的元素,然后遍历每个元素以形成一个带有基于data-date属性的链接a标签。

 function addDateLink() { document.querySelectorAll('[data-date]').forEach(div => { const date = div.getAttribute('data-date') div.innerHTML = `<a href="www.some-webpage.com/${date}">${date}</a>` }) }
 <div class="content" data-date="2020-05-27"></div> <div class="content" data-date="2020-05-28"></div> <div class="content" data-date="2020-05-29"></div> <input type="button" value="Display Link" onclick="addDateLink()"/>

you can use map-function for every and add a link您可以为每个使用地图功能并添加一个链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM