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

时间:2015-09-18 16:52:37

标签: javascript jquery html

只想询问如何在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>

1 个答案:

答案 0 :(得分:1)

您只需使用值替换网址中的细分,您甚至不需要jQuery来执行此操作。请参阅下面的工作示例。

&#13;
&#13;
function setLinkValue(value) {
  var link = document.getElementById('site-link');
  
  link.href = link.href.replace('putNatsvarHere', value);
}

//You would pass netsvar here
setLinkValue('ExampleValue');
&#13;
<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>
&#13;
&#13;
&#13;

您可以通过以下方式致电setLinkValue

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

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

&#13;
&#13;
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');
}
&#13;
<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>
&#13;
&#13;
&#13;