在HTML链接中使用动态JS变量

时间:2017-05-30 17:32:32

标签: javascript

我有一个动态的亚马逊链接,其中我试图重用一个动态的javascript变量,该变量在关键词的代码中的其他地方(此链接之前)使用...

<a href="https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Ddigital-music&field-keywords="'+val.sources[0].title+'>

OR

<script>
    $.each(track, function(index, val) {
    trackHtml  += '<a href="https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Ddigital-music&field-keywords='+val.sources[0].title+'" target="_blank" class="btn btn-primary" style="width:100%"><i class="fa fa-amazon fa-3x" aria-hidden="true" style="padding-bottom:3px"></i><br> Buy at Amazon</a>';});
</script>

可以这样做吗?如果是这样,上面的语法不起作用。我是否必须完全放在JS中并进行html输出?

这是我上面解释之前的代码 - 所以我调用并将变量创建为JSON文件&#34;

sources: [{
   track_id: '{$row['id']}',
   title: \"{$row['title']}\",
   artist: '{$row['artist']}',
   src: \"{$row['source_url']}\",
   poster: \"{$row['source_poster']}\",
   type: 'audio/mp3'
}],";

2 个答案:

答案 0 :(得分:0)

您需要首先提出字符串然后将其应用于HTML元素:

&#13;
&#13;
// Get a reference to the link
var link = document.getElementById("theLink");

// Faking the data for our purposes
var val = {};
val.sources = [{
  title:"TEST"
}];

// Append to the href
link.href += val.sources[0].title;

// Test
console.log(link.href);
&#13;
<a id="theLink" href="https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Ddigital-music&field-keywords=">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以这样做:

<a href="https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Ddigital-music" onclick="location.href=this.href+'&keywords='+val.sources[0].title;return false;">Link</a>