将生成的JavaScript网址放入“<a href="{{Text here}}">`

时间:2017-03-09 08:36:20

标签: javascript html

So, I have an external JavaScript that generates 4 numbers and puts them between 2 parts of text, like this

document.getElementById("gen3").textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669";

<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>

<div id="gen3"></div>

It generates properly and selecting it and opening it in a new tab works perfectly, but I'd like to make it easier by placing it directly into an href.

2 个答案:

答案 0 :(得分:0)

您可以在HTML中将div更改为a(锚标记),并使用JavaScript中的href属性设置单击时使用的网址目标。您还可以选择将其textContent设置为相同的值,这使得使用该工具的用户更清楚地了解他们点击链接时的确切位置。

gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"

Demo Snippet

var gen3 = document.getElementById("gen3")

function postmessage() {
  // Pretending these are "random" values, and assuming you have the code for them already
  var first = 1,
    fnum = 2,
    snum = 3,
    tnum = 4

  // Later...
  gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
}
<p>
  <input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<p>
  <a id="gen3"></a>
</p>

答案 1 :(得分:0)

您可以在anchor

中创建div标记

然后你可以这样做

<强> JS

document.getElementById("linkText").setAttribute('href','www.google.com')

<强> HTML

<div id="gen3">
 <a href="" id="linkText">Click Me</a>
</div>

DEMO