首页 > 解决方案 > 如何从捕获的 innerHTML 值构造 JavaScript 中的链接?

问题描述

假设我有

    <a href="#" id="someid">findme</a>  (innertext can be whatever other than findme)

当我点击“findme”时,我想重定向到页面“/?q=findme”。(应该在 /?q= 之后插入值以创建新链接,并且页面应该重定向到该链接。)如何使用 javascript 做到这一点?

标签: javascripthtml

解决方案


获取链接的内部文本并修改 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>


推荐阅读