简体   繁体   中英

Placing generated JavaScript URL into `<a href=“{{Text here}}”>`

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.

You can change your div into an a (anchor tag) in your HTML and use its href property in JavaScript to set the URL destination used when you click it. You can also choose to set its textContent to the same value, which makes it clearer to people using the tool where exactly they are going when they click the link.

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> 

You can create an anchor tag inside the div

Then you can do like this

JS

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

HTML

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

DEMO

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM