just want to ask if how to add a variable in the href? for example this is the my 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>
I want to insert it into my a
tag in href
<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>
You can just replace a segment in the URL with the value, and you don't even need jQuery to do it. See the working example below.
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>
You could call setLinkValue
in this way:
var natsvar = getCookie("nats");
setLinkValue(natsvar);
To update multiple elements, you could use getElementsByClassName
and loop through them.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.