如何生成动态href

How to generate Dynamic href?

本文关键字:href 动态 何生成      更新时间:2023-09-26

我想使用javascript或HTML生成动态的href链接。

<a target="_self" href="detail.aspx?videoID={@ID}">
    <img src="{@AlternateThumbnailUrl}" alt="{@Title}" width="400" />
</a>

所以你可以在javascript中用字符串连接构建一个href。如果没有一个更具体的例子,我不知道你想传递什么样的参数

var example = "ww.google.com";
var exampleHref = "http://" + google;
然后你可以用这个属性创建一个新的DOM节点
// get some parent div with id
var div = document.getElementById('someDiv');
// create <a> tag
var tag = document.createElement(a);
// set the href attribute
tag.setAttribute('href', exampleHref);
// append the node to the parent
div.appendChild(tag);

因此,给定额外的信息,可以编写一个JavaScript函数来创建所需的字符串,然后从中获取结果并创建所需的DOM节点。

接受要插入它的父节点,然后是上面给出的参数

function insertDOM(parentNode, id, altUrl, title) {
    // create <a> tag and <img> tag
    var aTag = document.createElement(a);
    var imgTag = document.createElement(img);
    // set the appropriate properties
    aTag.setAttribute(href, id);
    aTag.setAttribute(target,'_self');
    imgTag.setAttribute(src, altUrl);
    imgTag.setAttribute(alt, alt);
    imgTag.setAttribute(width, 400);
    // attach the img tag to a, then a to the parent
    aTag.appendChild(imgTag);
    parentNode.appendChild(aTag);
}

你可以这样命名它:

// get parent node
var div = document.getElementById('something');
insertDOM(div, id, altUrl, title);