[英]how to insert variable values in link href using javascript?
只想问一下如何在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
以下方式调用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.