2015-09-18 151 views
0

只想问如何在href中添加一个变量? 例如,这是我的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> 

我想将它插入到我a标签中的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> 
+0

可以使用onclick属性和调用的getCookie方法 –

+0

我准备怎么使用?你能给我一个示例代码吗? –

回答

1

只需更换同价值的地址段,而你不知道甚至不需要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>

+0

它没有为我工作。但我认为这是我想要发生的方式 –

+0

我的发送链接变成链接这个 Exclusive February Sale! 而不是putNatsvarHere –

+0

的值你能帮我@drew吗? –

相关问题