[英]How to construct a link in JavaScript from captured innerHTML value?
假设我有
<a href="#" id="someid">findme</a> (innertext can be whatever other than findme)
当我点击“findme”时,我想重定向到“/?q=findme”页面。 (该值应该在 /?q= 之后插入以创建一个新链接,页面应该重定向到该链接。)如何使用 javascript 做到这一点?
获取链接的内部文本并修改 href 属性以指向您的首选位置。
const linkElement = document.getElementById('someid'); //get your link element by id const innerValue = linkElement.innerText // get inner text value linkElement.href = '/?q=' + innerValue // set href attribute
<a href="#" id="someid">findme</a>
像这样
const lnk = document.getElementById("someid"); // direct access lnk.href = "/?q="+lnk.textContent; // set the href attribute
<a href="#" id="someid">findme</a>
更多信息:
[...document.querySelectorAll("#container a")] // get the html node list of anchors in the container .forEach(lnk => lnk.href = "/?q="+lnk.textContent); // set each of the hrefs
<div id="container"> <a href="#" id="find">findme</a> <a href="#" id="goto">goto</a> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.