简体   繁体   English

JS:动态添加链接到某个类的所有元素

[英]JS: Add link dynamically to all elements of certain class

I work in a system where we have these elements representing a part of an audio clip, and a timeline for the audio that is browsable (click around to play different parts).我在一个系统中工作,其中我们有这些元素代表音频剪辑的一部分,以及可浏览的音频时间线(点击周围播放不同的部分)。 However, the elements representing the parts of the audio clip does not actually link to the parts of the audio.. (so no "click this to play this part").但是,代表音频剪辑部分的元素实际上并没有链接到音频的部分..(所以没有“点击这个播放这个部分”)。

I have deducted that it is possible to link to a specific part of the call via for example: http://thelink.com/timeline?startms=%221600326183999%22 .我推断可以通过例如: http://thelink.com/timeline?startms=%221600326183999%22 : http://thelink.com/timeline?startms=%221600326183999%22链接到呼叫的特定部分。 And that the elements all have an attribute called "startms", for example:并且所有元素都有一个名为“startms”的属性,例如:

<div class="segment-item" startms="1600326183999"></div>

Is there any way I could loop through all the elements in the page with the class "segment-item" and add a href="" with the value of their individual "startms" value to the link ( http://thelink.com/timeline?startms=%22TheValueHere%22 ).有什么方法可以让我使用“segment-item”类遍历页面中的所有元素,并将带有它们各自“startms”值的值的 href="" 添加到链接( http://thelink.com/timeline?startms=%22TheValueHere%22 )。

Then finally, since I cannot build an addon to my browser for this, would it be possible to make a snipped which can be pasted into the console for easy use when I need it?最后,由于我无法为此在浏览器中构建插件,是否可以制作一个可以粘贴到控制台中以便在我需要时易于使用的片段? Any other suggestions to making such a thing be easily accessible for usage without making or using an addon for chrome?有没有其他建议可以让这样的东西很容易使用,而无需为 chrome 制作或使用插件?

If you want to add the link to the element, you should add it like that如果要将链接添加到元素,则应该像这样添加

const elements = document.getElementsByClassName("segment-item")
    for (element of elements) {
        const a = document.createElement("a")
        a.href = `http://thelink.com/timeline?startms=%22${element.getAttribute("startms")}%22`
        a.innerText = "LINK NAME"

        element.appendChild(a)
    }

Adding a link based on element properties goes like this添加基于元素属性的链接是这样的

const elements = document.getElementsByClassName("segment-item")
for (element of elements) {
    element.innerHTML = `<a href="http://thelink.com/timeline?startms=%22${element.getAttribute("startms")}%22">
                              Link name
                         </a>`
}

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

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