gpt4 book ai didi

javascript - 如何使用javascript在链接href中插入变量值?

转载 作者:行者123 更新时间:2023-12-03 08:51:24 27 4
gpt4 key购买 nike

只是想问一下如何在href中添加变量?例如,这是我的 javascript:

    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
function setLinkValue(value) {
var numItems = $('[id^=site-]').length;

for (i = 0; i < numItems; i++) {
var link = document.getElementsByClassName('site-link');
link.href = link.href.replace('putNatsvarHere', value);
}

}

//You would pass netsvar here
setLinkValue('ExampleValue');

});
</script>

我想将其插入到 href 中的 a 标记中

<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title" target="_self">Exclusive February Sale!</a><br>

<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title-link" target="_self">Sale!</a>
<br>
<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title-link pink-play" target="_self"> February Sale!</a>

最佳答案

您只需将 URL 中的某个段替换为值即可,甚至不需要 jQuery 来完成此操作。请参阅下面的工作示例。

function setLinkValue(value) {
var link = document.getElementById('site-link');

link.href = link.href.replace('putNatsvarHere', value);
}

//You would pass netsvar here
setLinkValue('ExampleValue');
<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title-link pink-play" target="_self">Exclusive February Sale!</a>

您可以通过以下方式调用setLinkValue:

var natsvar = getCookie("nats");
setLinkValue(natsvar);

要更新多个元素,您可以使用 getElementsByClassName 并循环遍历它们。

function setLinkValue(link, value) {
link.href = link.href.replace('putNatsvarHere', value);
}

var elements = document.getElementsByClassName('title-link');
var i = 0;

for (i = 0; i < elements.length; i++) {
//You would pass netsvar here
setLinkValue(elements[i], 'ExampleValue');
}
<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" class="title-link pink-play" target="_self">Exclusive February Sale!</a>
<a href="http://example.com/putNatsvarHere/" class="title-link pink-play" target="_self">Another link</a>

关于javascript - 如何使用javascript在链接href中插入变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32657265/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com